美文网首页
day9作业

day9作业

作者: xue_y | 来源:发表于2019-01-04 20:14 被阅读0次
    1. 编写一个函数,求1+2+3+...+N
    def xy_sum(n):
        sum = 0
        for i in range(1, n+1):
            sum += i
        print(sum)
    
    
    xy_sum(10)
    
    1. 编写一个函数,求多个数中的最大值
    def get_max(*num):
        # print(max(num))
        max1 = num[0]
        for item in num:
              if item > max1
              max1 = num
        return max1
    
        
    print(get_max(2, 5, 7, 9, 3, 0))
    
    1. 编写一个函数,实现摇色子的功能,打印n个色子的点数和
    import random
    def roll_dice(n):
        sum = 0
        for i in range(1, n+1):
            num = random.randint(1, 6)
            sum += num
        print(sum)
    
    
    roll_dice(4)
    
    1. 编写一个函数,交换指定字典的key和value。
      例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
    def chage_word(dict1:dict):
        dict2 = {}
        for key in dict1:
            dict2[dict1[key]] = key
        print(dict2)
    
    
    chage_word({'a':1, 'b':2, 'c':3})
    
    1. 编写一个函数,三个数中的最大值
    def get_max(*num):
        print(max(num))
    
        
    get_max(2, 5, 7, 9, 3, 0)
    
    1. 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
      例如:'12a&bc12d--' ---> 打印'abcd'
    def change_str(str1:str):
        str2 = ' '
        for char in str1:
            if 'a' <= char <= 'z' or 'A' <= char <= 'Z':
                str2 += char
        print(str2)
    
    
    
    change_str('12a23bc12d')
    
    1. 写一个函数,求多个数的平均值
    def new_average(*num):
        print(sum(num) / len(num))
    
    
    new_average(8, 10, 14, 16)
    
    1. 写一个函数,默认求10的阶层,也可以求其他数的阶层
    def factorial(n=10):
        """求指定数的阶乘"""
        num = 1
        for i in range(1, n+1):
            num *= i
        print('%d的阶乘是%d' % (n, num))
    
    
    factorial()
    
    1. 写一个函数,可以对多个数进行不同的运算
      例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
      operation('-', 10, 9) ---> 求 10-9的结果
      operation('', 2, 4, 8, 10) ---> 求 24810的结构
    def operation(*num):
        tuple1 = num[1:]
        if num[0] == '+':
            print('和为:%d' % sum(tuple1))
        elif num[0] == '-':
            sub_num = tuple1[0]
            for num1 in tuple1[1:]:
                sub_num -= num1
            print(sub_num)
        else:
            multiply_num = 1
            for num2 in tuple1:
                multiply_num *= num2
            print(multiply_num)
    
    
    operation('+', 1, 2, 3)
    operation('-', 10, 9)
    operation('*', 2, 4, 8, 10)
    

    相关文章

      网友评论

          本文标题:day9作业

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