Day-作业

  1. 编写⼀个函数,求1+2+3+...+N
def lei_jao(n):
    sum1 = 0
    for x in range(1,n+1):
        sum1 += x
    print(sum1)
  1. 编写⼀个函数,求多个数中的最⼤值
def print_max(list1):
    print(max(list1))
  1. 编写⼀个函数,实现摇⾊⼦的功能,打印n个⾊⼦的点数和
import random
def dianshu_sum(n):
    x =0
    list1=[]
    while x < n:
        num = random.randint(1, 7)
        list1.append(num)
        x+=1
    print(sum(list1),list1)


dianshu_sum(8)
点数是: 31 
 [6, 2, 4, 3, 7, 2, 1, 6]
  1. 编写⼀个函数,交换指定字典的key和value。
    例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
dict2 = {'a': 1, 'b': 2, 'c': 3}
def exchange_key_value(dict1):
    dict3 = {}
    for key in dict1:
        dict3.update({dict1[key]:key})
    print(dict3)
exchange_key_value(dict2)

{1: 'a', 2: 'b', 3: 'c'}
  1. 编写⼀个函数,三个数中的最⼤值
def num_max(a,b,c):
    num = max(a,b,c)
    print(num)
num_max(9,8,7)

9
  1. 编写⼀个函数,提取指定字符串中的字⺟,然后拼接在⼀起后打印出来
    例如:'12a&bc12d' ---> 打印'abcd'
def word(str1):
    str2 = ''
    for x in range(len(str1)):
      if ('a'<= str1[x] <='z')or ('A'<= str1[x]<='Z'):
          str2 += str1[x]
    print(str2)
word('abc123AD')

abcAD
  1. 写⼀个函数,求多个数的平均值
def average_num(num):
    sum1 = 0
    for x in range(len(num)):
        sum1 = sum1 + num[x]
        sum2 = sum1 / len(num)
 print('%.2f'%sum2)
average_num([10,20,30,40])

25.0

  1. 写⼀个函数,默认求10的阶层,也可以求其他数的阶层
def jiecheng(num = 10):
    sum1 =1
    for x in range(1,num):
        sum1 = sum1 * x
    print(sum1)
jiecheng(4)

jiecheng(4)
jiecheng()

6
362880
  1. 写⼀个函数,可以对多个数进⾏不同的运算
    例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
    operation('-', 10, 9) ---> 求 10-9的结果
    operation('', 2, 4, 8, 10) ---> 求 24810的结构
def yunsuan(tuple1):
    sum1 = 1
    flag ,*num = tuple1
    if flag == '+':
        sum1 = sum(num)
    elif flag == '*':
        for x in range(len(num)):
            sum1 = sum1*num[x]
    print(sum1 )
yunsuan(('+',1,2,3,4))
yunsuan(('*',1,2,3,4))

10
24

推荐阅读更多精彩内容