美文网首页
2018-08-29作业

2018-08-29作业

作者: Smilebest | 来源:发表于2018-08-30 16:34 被阅读9次
    1.编写一个函数,求1+2+3+...+N
    def sum_he(*number):
        sum = 0
        # 取出每一个元素
        for item in number:
            # 元素求和
            sum += item
        print(sum)
    sum_he(1,2,3)
    print('==========')
    
    2.编写一个函数,求多个数中的最大值
    def max_number(*number):
        max_number = max(number)
        print(max_number)
    max_number(1,5,2,4,9,10,20,50,100)
    print('==========')
    
    3.编写一个函数,实现摇色子的功能,打印n个色子的点数
    def shai_number(n):
        import random
        count = []
        for x in range(1,n+1):
            number = random.randint(1,6)
            count.append(number)
        return count
    count = shai_number(7)
    print(count)
    print('==========')
    
    4.编写一个函数,交换指定字典的key和value
    def change_dict(dict1:dict):
        dict2 = {} # 建立一个空的字典
        for key1 in dict1:
            dict2[dict1[key1]] = key1
        return dict2
    
    dict1 ={'a':1,'b':2,'c':3}
    dict2 = change_dict(dict1)
    print(dict2)
    print('==========')
    
    5.编写一个函数,三个数中的最大值
    def max_number1(*number1):
        max_number1 = max(number1)
        print(max_number1)
    max_number1(7,8,9)
    print('==========')
    
    6.编写一个函数,提取指定字符串中的所有字母,然后拼接在一起后打印出来
    def str1(a):
        str2 = ''
        for x in a:
            if x.isalpha():
                str2 += x
        return str2
    str2 = str1('12a&bc12d')
    print(str2)
    print('==========')
    
    7.写一个函数,求多个数的平均值
    def mean1(*number3):
        sum1 = 0
        for item in number3:
            sum1 += item
            long = len(number3)
        mean2 = int (sum1/long)
        return mean2
    mean1(1,2,3)
    mean2 = mean1(1,2,3)
    print(mean2)
    print('==========')
    
    8.写一个函数,默认求10!,也可以求其他数的阶乘
    def jie_cheng(number4 = 10):
        fac = 1
        for x in range(1,number4+1):
            fac *= x
        return fac
    fac = jie_cheng(5)
    print(fac)
    print('==========')
    
    9.写一个函数,可以对多个数进行不同的运算
    def operation (a:str,*number9):
        if a == '+':
            new_operation = 0
            for item in number9:
                new_operation += item
                print(new_operation)
            return new_operation
        elif a == '-':
            new_operation = 0
            for item in number9:
                new_operation -= item
                print(new_operation)
            return new_operation
        elif a == '*':
            new_operation = 1
            for item in number9:
                new_operation *= item
                print(new_operation)
            return new_operation
        else :
            new_operation = 1
            for item in number9:
                new_operation /= item
                print(new_operation)
            return new_operation
    
    print(operation('+',1,2,3,4,5))
    

    相关文章

      网友评论

          本文标题:2018-08-29作业

          本文链接:https://www.haomeiwen.com/subject/kgldwftx.html