- 编写⼀个函数,求1+2+3+...+N
def my_sum(num:int):
sum1 = 0
for x in range(num+1):
sum1 += x
return sum1
- 编写⼀个函数,求多个数中的最⼤值
def wjj_max(*args):
max1=args[0]
for num in args:
if num > max1:
max1=num
return max1
- 编写⼀个函数,实现摇⾊⼦的功能,打印n个⾊⼦的点数和
import random
def my_game(The_number_of_dice:int):
input_str=input('输入1摇色子,输入end退出')
if input_str == '1':
sum1 = 0 #储存色子总点数
count = 0
for _ in range(The_number_of_dice):
num1 = random.randint(1,6)
count += 1
print('第%d个色子点数为%d'%(count,num1))
sum1 += num1
return '%d个色子总点数是%d'%(The_number_of_dice,sum1)
else:
print('成功退出!!')
print(my_game(6))
- 编写⼀个函数,交换指定字典的key和value。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def exchange_dict(dict1:dict):
dict2={}
for key in dict1:
dict2.setdefault(dict1[key],key)
return dict2
print(exchange_dict({'a':1, 'b':2, 'c':3}))
dict1={'a':1, 'b':2, 'c':3}
gen2=dict((value,key) for key,value in dict1.items())
print(gen2)
- 编写⼀个函数,三个数中的最⼤值
def my_max(*args):
return max(*args)
print(my_max(1,2,3))
- 编写⼀个函数,提取指定字符串中的所有的字⺟,然后拼接在⼀起后打例如:'12a&bc12d--' ---> 打印'abcd'
def joint_str(str1):
str2=''
for x in str1:
if 'a' <= x <= 'z' or 'A' <= x <='Z':
str2 += x
return str2
print(joint_str('12a&bc12d--'))
- 写⼀个函数,求多个数的平均值
def mean(*args):
sum1 = 0
for x in args:
sum1 += x
return sum1/len(args)
print(mean(10,20,30,40,50))
- 写⼀个函数,默认求10的阶层,也可以求其他数的阶层
def factorial(num=10):
product = 1
for x in range(1,num+1):
product *= x
return product
print(factorial())
- 写⼀个函数,可以对多个数进⾏不同的运算
例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('', 2, 4, 8, 10) ---> 求 24810的结
def operation(str1:str,*args:float):
if str1 == '+':
sum = 0
for x in args:
sum += x
return sum
elif str1 == '-':
list1=list(args)
num = list1[0]
for x in list1[1::]:
num -= x
return num
elif str1 == '*':
product = 1
for x in args:
product *= x
return product
elif str1 == '/':
list1=list(args)
num2 = list1[0]
for x in list1[1::]:
num2 /= x
return num2
else:
print('暂时不支持其他算法')
print(operation('+',24,4,6)) # 34
print(operation('-',24,4,6)) # 14
print(operation('*',24,4,6)) # 576
print(operation('/',24,4,6)) #1.0
网友评论