1.编写一个函数,求1+2+3+N
def num(n):
sum = 0
for n in range(n+1):
sum += n
return sum
n = int(input('请输入你想要计算的数字:'))
result = num(n)
print(result
# 结果:
请输入你想要计算的数字:55
1540
2.编写一个函数,求多个数中的最大值
def num(list1:list):
max = 0
for item in list1:
if item > max:
max = item
return max
result = num([1,352,43215,5436,314])
print(result)
# 结果:43215
3.编写一个函数,实现一个摇骰子的功能,打印n
个骰子的和。
import random
def tou_zi(n,number):
sum = 0
for x in range(n):
sum += number
return sum
n = int(input('请问你要摇几个骰子:'))
result = tou_zi(n,random.randint(1,6))
print(result)
#结果:
请问你要摇几个骰子:7
24
4、编写一个函数,交换指定字典的key和value。
def exchange(dict1:dict):
dict2 = {}
for key,value in dict1.items():
dict2[value] = key
return dict2
result = exchange({'a':1,'b':2,'c':3})
print(result)
#结果:{1: 'a', 2: 'b', 3: 'c'}
5.编写一个函数,三个数中的最大值
def three_number(a,b,c):
#可以直接 return max(a,b,c)
if a > b > c:
return a
elif b > a > c:
return b
else:
return c
a = int(input('请输入一个数字:'))
b = int(input('请输入一个数字:'))
c = int(input('请输入一个数字:'))
result = three_number(a,b,c)
print(result)
#结果:
请输入一个数字:12
请输入一个数字:18
请输入一个数字:10
18
6.编写一个函数,提取指定字符串中的所有字母,然后拼接在一起后打印出来
def eng1(char1):
char2 = ''
for char in char1:
if char.isalpha():
char2 += char
return char2
result = eng1('12a&bc12d--')
print(result)
结果:abcd
7.编写一个函数,求多个数的平均值
def avge(number):
sum = 0
avg = 0
for index in range(len(number)):
sum += number[index]
continue
avg = sum / index
return avg
number = [10,214,3215,325235,5235]
result = avge(number)
print(result)
# 结果:83477.25
8.写一个函数,默认求10的阶乘,也可以求其他数的阶乘。
def jie_cheng(number = 10):
sum = 1
for x in range(1,number+1) :
sum *= x
return sum
result = jie_cheng()
print(result)
# 结果:3628800
9.写一个函数,可以对多个数进行不同的运算
def operation(str1,*number):
count = 0
count2 = 1
if str1 == '+':
for n in number[:]:
count += n
return count
elif str1 == '-':
count = number[0]
for n in number[1:]:
count -= n
return count
elif str1 == '*':
for n in number[:]:
count2 *= n
return count2
elif str1 == '/':
count2 = number[0] / number[1]
return count2
elif str1 == '**':
count2 = number[0]**number[1]
return count2
elif str1 == '//':
count2 = number[0] // number[1]
return count2
elif str1 == '%':
count2 = number[0] % number[1]
return count2
else:
print('不支持这种运算符')
print(operation('+',2,3,5,6))
print(operation('-',2,3,5,6))
print(operation('*',2,3,5,2))
print(operation('/',2,3))
print(operation('//',2,3))
print(operation('**',2,3))
print(operation('%',2,3))
result:
16
-12
60
0.6666666666666666
0
8
2