1.編寫函數(shù)蜒什,求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.編寫一個函數(shù),求多個數(shù)中的最大值
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.編寫一個函數(shù)潮售,實現(xiàn)搖骰子的功能蚁飒,打印N個骰子的點數(shù)和
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.編寫一個函數(shù)动壤,交換指定字典的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.編寫一個函數(shù)萝喘,提取指定字符串中所有的字母淮逻,然后拼接在一起產(chǎn)生一個新的字符串
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.寫一個函數(shù)琼懊,求多個數(shù)的平均值
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.寫一個函數(shù),默認求10的階乘爬早,也可以求其他數(shù)字的階乘
def factorial(n):
sum1 = 1
x = 1
while x < (n+1):
sum1 *= x
x += 1
print(sum1)
factorial(10)