1.编写函数,求1+2+3+…N的和
def chy_sum(n):
sum1 = 0
x = 1
while x < (n+1):
sum1 += x
x += 1
print(sum1)
chy_sum(100)
2.编写一个函数,求多个数中的最大值
def max_value(*num):
max1 = num[0]
for index in range(1,len(num)):
if num[index] > max1:
max1 = num[index]
print(max1)
max_value(1,2,3,4,10,5,32)
3.编写一个函数,实现摇骰子的功能,打印N个骰子的点数和
def dice_sum(n):
x=1
sum1 = 0
import random
while x < n+1:
a = random.randint(1,6)
sum1 += a
x += 1
print(sum1)
dice_sum(5)
4.编写一个函数,交换指定字典的key和value
def exchange_dict(dict1:dict):
new_dict = {}
for key in dict1:
new_dict[dict1[key]] = key
print(new_dict)
dict2={'a':1, 'b':2, 'c':3}
exchange_dict(dict2)
5.编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
def stitching_letter(str1):
str2 = ""
for chr1 in str1:
if "A" <= chr1 <= "Z" or "a" <= chr1<= "z":
str2 += chr1
print(str2)
stitching_letter("12a&bc12d-+")
6.写一个函数,求多个数的平均值
def chy_average(*num):
sum1 = 0
for x in num:
sum1 += x
print(sum1/len(num))
chy_average(1,2,3,4,5,6)
7.写一个函数,默认求10的阶乘,也可以求其他数字的阶乘
def factorial(n):
sum1 = 1
x = 1
while x < (n+1):
sum1 *= x
x += 1
print(sum1)
factorial(10)