1.编写一个函数,求1+2+3+···+N
def my_sum(N):
my_list = []
for num in range(N):
my_list.append(num+1)
return sum(my_list)
print('1+2+3+···+N的和为:%d' % (my_sum(6)))
2.编写一个函数,求多个数中的最大值
def my_max(*num):
return max(*num)
print('最大值为:%d' % my_max(12,13,14,15,2,21,99,87))
print('最大值为:%d' % my_max(1,2,3,4,5))
3.编写一个函数,实现摇色子的功能,打印n个色子的点数和
import random
def my_dice(N):
sum = 0
for _ in range(N):
num = random.randint(1,6)
print('每次色子的点数:%d' % (num))
sum += num
return sum
print('n次色子的点数和:%d' % (my_dice(5)))
4.编写一个函数,交换指定字典的key和value
def my_exchange(dict_exchange:dict):
for key in dict_exchange:
key_exchange = key
value = dict_exchange[key]
del dict_exchange[key] # 为什么不能直接添加键值对,
# 报错RuntimeError: dictionary changed size during iteration,说:字典在迭代过程中改变了大小
dict_exchange[value] = key_exchange
return dict_exchange
print(my_exchange({'a':1, 'b':2, 'c':3,'d':4})) # 成功,但是加了'd':4就失败
print(my_exchange({'Q':'q', 'W':'w', 'E':'e', 'R':'r'})) # 对换失败,遍历key时,新的key又被遍历
# 因为原字典在遍历过程中被改变了键值对,所以会遍历失败,和remove一个道理,因此,创建一个新字典,添加新的键值对
def my_exchange(dict_exchange:dict):
new_dict_exchange = {}
for key in dict_exchange:
key_exchange = key
value = dict_exchange[key]
# del dict_exchange[key] # 为什么不能直接添加键值对,报错RuntimeError: dictionary changed size during iteration
new_dict_exchange[value] = key_exchange
return new_dict_exchange
print(my_exchange({'a':1, 'b':2, 'c':3,'d':4}))
print(my_exchange({'Q':'q', 'W':'w', 'E':'e', 'R':'r'}))
5.编写一个函数,求三个数中的最大值
def my_max(a, b, c):
return max(a, b, c)
print(my_max(99, 123, 19))
6.编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
def my_str(str1:str):
list1 = []
for item in str1:
if 'a' <= item <='z' or 'A' <= item <='Z':
list1.append(item)
return ''.join(list1) # return 前面的缩进很重要,放在不同的位置,返回值不同
print(my_str('231ji2ds12aj12'))
7.编写一个函数,求多个数的平均值
def my_average(*num): # num = (1,2,3,4,5) 是个元组
return sum(num)/len(num)
print(my_average(10, 2, 30, 4, 50))
8.编写一个程序,默认求10的阶乘,也可以求其他数的阶乘
def my_factorial(num=10):
sum = 1
for item in range(1,num+1):
sum *= item
return sum
print(my_factorial())
9.编写一个程序,可以对多个数进行不同的运算
def my_operation(way,*num):
if str(way) == '+':
return sum(num)
elif str(way) == '-':
return num[0] - num[1]
elif str(way) == '*':
number = 1
for item in num:
number *= item
return number
print(my_operation('+', 100, 200, 300))
print(my_operation('-', 100, 39))
print(my_operation('*', 5, 4, 3, 2, 1))
网友评论