01-04 作业

  1. 编写一个函数,求1+2+3+...+N
def  yc_sum(N:int):
    sum1 = sum(range(1,N+1))
    print(sum1)
yc_sum(5)
  1. 编写一个函数,求多个数中的最大值
def yc_max(*nums):
    '''求多个数的最大值'''
    max1=nums[0]
    for item in nums:
        if item > max1:
            max1 = item
    return max1
print(yc_max(20,9,8,49,89))
  1. 编写一个函数,实现摇色子的功能,打印n个色子的点数和
from random import randint
def dice(n):
    '''n个色子'''
    sum1=0
    for _ in range(n):
        point = randint(1,6)
        print('点数:',point)
        sum1 += point
    return sum1
print(dice(4))
  1. 编写一个函数,交换指定字典的key和value。
    例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def change(dict:dict):
#通过生成器实现
    new_dict ={value:key for key,value in dict.items()}
    print(new_dict)

change({'a':1, 'b':2, 'c':3})
def change(dict1:dict):
    '''交换键值,先取出键值对,交换位置后再添加进字典'''
    for key in dict1.copy():
        # 不用copy的话,如果出现{‘a':b,'b':c}这样的字典,执行完一次键值对操作后,元素会被覆盖。程序不会报错,但是字典长度变了。
        value = dict1.pop(key)
        dict1[value]=key
dict2={'a':1, 'b':2, 'c':3}
change(dict2)
print(dict2)
  1. 编写一个函数,三个数中的最大值
def  yc_max(a,b,c):
    num = [a,b,c]
    max_num=max(num)
    print(max_num)
yc_max(5,4,6)
  1. 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
    例如:'12a&bc12d--' ---> 打印'abcd'
def  yc_zimu(str1:str):
   zimu= []
   for x in str1:
       if 'a'<= x <='z' or 'A' <= x <='Z':
           zimu.append(x)
   new_str=''.join(zimu)
   print(new_str)


yc_zimu('12a&bc12d--')
  1. 写一个函数,求多个数的平均值
def  yc_ave(*num):
   sum_num=sum(num)
   print('平均值:',sum_num/len(num))
yc_ave(5,4,6,8,2)
  1. 写一个函数,默认求10的阶层,也可以求其他数的阶层
def factorial(n=10):
    """求指定数的阶乘"""
    sum1 = 1
    for x in range(1, n+1):
        sum1 *= x
    print('%d的阶乘是:%d' % (n, sum1))
factorial(5)
  1. 写一个函数,可以对多个数进行不同的运算
    例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
    operation('-', 10, 9) ---> 求 10-9的结果
    operation('*', 2, 4, 8, 10)
def  operatio(str1:str,*num):
    jia=0# 存 和
    jian=0 # 存 差
    cheng=1 #存 积
    chu = 0 #存 余
    if str1=='*':
        for x in num:
            cheng *=x
        print(cheng)
    elif str1=='+':
        for x in num:
            jia += x
        print(jia)
    elif str1 == '-':
        jian = num[0]-num[1]
        print(jian)
    else:
        chu = num[0] / num[1]
        print(chu)
operatio('+',1,2,3)
operatio('*',2,3,4)
operatio('-',4,5)
operatio('/',5,4)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 编写一个函数,求1+2+3+...+N 2. 编写一个函数,求多个数中的最大值 3. 编写一个函数,实现摇色...
    生命的怒放阅读 838评论 0 0
  • 编写一个函数,求1+2+3+...+N 编写一个函数,求多个数中的最大值 编写一个函数,实现摇色子的功能,打印n个...
    xxxQinli阅读 2,675评论 0 0
  • 1.编写一个函数,求1+2+3+...+N 2.编写一个函数,求多个数中的最大值 3.编写一个函数,实现摇⾊子的功...
    百而所思阅读 1,761评论 0 0
  • 8月22日-----字符串相关 2-3 个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息。显示的消...
    future_d180阅读 4,538评论 0 1
  • 一分钟弄清几个易混淆概念 在葡萄酒的世界里,有几个概念是总让人摸不着头脑的:葡萄酒就是红酒吗?那白葡萄酒怎么办...
    灬柒柒灬阅读 2,415评论 0 0