- 编写一个函数,求1+2+3+...+N
def sum1(N):
sum = 0
for index in range(1,N+1):
sum += index
print('1~%d的和是:'%N,end='')
return sum
print(sum1(5))
结果:
1~5的和是:15
2.编写一个函数,求多个数中的最大值
def max(list:list):
list.sort()
return list[len(list)-1]
print('最大值是 ==》',end='')
print(max([1,32,12,45.3,5]))
结果:
最大值是 ==》45.3
3.编写一个函数,实现摇色子的功能,打印n个色子的点数和
import random
def dicl(): #摇色子
n = int(input('输入‘1’开始摇色子:'))
rand = 1
if n == 1:
rand = random.randint(1,6)
print(rand)
list.append(rand)
list = []
count = 0
while True:
dicl()
count += 1
n = int(input('输入‘1’继续摇色子,输入‘2’停止摇色子:'))
if n == 1:
continue
elif n == 2:
break
else:
print('输入不合法!')
exit('程序终止!')
sum1 = sum(list)
print('%d个色子和为:%d'%(count,sum1))
结果:
输入‘1’开始摇色子:1
5
输入‘1’继续摇色子,输入‘2’停止摇色子:1
输入‘1’开始摇色子:1
4
输入‘1’继续摇色子,输入‘2’停止摇色子:2
2个色子和为:9
4.编写一个函数,交换指定字典的key和value。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def change_dict(list1:dict):
list_keys,list_values = [],[]
list2 = {}
list_keys = list1.keys()
list_values = list1.values()
list2 = list2.fromkeys(list_values) #先得到交换后的keys
count1 = 0
for values in list_values: #赋值交换后keys对应的values
count2 = 0
for keys in list_keys:
if count2 == count1:
list2[values] = keys
count2 += 1
count1 += 1
print('改变前==》',list1)
return list2
print('改变后==》',change_dict({1:'a', 2:'b', 3:'c'}))
结果:
改变前==》 {1: 'a', 2: 'b', 3: 'c'}
改变后==》 {'a': 1, 'b': 2, 'c': 3}
5.编写一个函数,三个数中的最大值
def max(*nums):
list_new = list(nums)
list_new.sort()
return list_new[len(list_new) - 1]
print('最大值为:',max(1,3,2))
结果:
最大值为: 3
6.编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
如: '12a&bc12d' ---> 'abcd'
def joint(str1:str):
str2 = ''
for item in str1:
if 'a' <= item <= 'z' or 'A' <= item <= 'Z':
str2 += item
return str2
print(joint('12a&bc12d'))
结果:
abcd
7.写一个函数,求多个数的平均值
def average_new(*num):
sum = 0
for item in num:
sum += item
average = sum / len(num)
return average
print(average_new(2,3,5,3))
结果:
3.25
8.写一个函数,默认求10的阶乘,也可以求其他数的阶乘
def factorial(num):
product = 1
for i in range(1,num+1):
product *= i
print(num,end='')
return product
print('的阶乘是:%d'%(factorial(10)))
结果:
10的阶乘是:3628800
9.写一个函数,可以对多个数进行不同的运算
例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('', 2, 4, 8, 10) ---> 求 24810的结果
方法一
def operation(str1:str, *args):
arg = list(args)
operation = arg[0]
if str1 == '+':
for item in arg[1:]:
operation = operation + item
return operation
elif str1 == '*':
for item in arg[1:]:
operation = operation * item
return operation
elif str1 == '-':
for item in arg[1:]:
operation = operation - item
return operation
print(operation('+',10,9))
print(operation('-', 10, 9))
print(operation('*', 2, 4, 8, 10))
结果:
19
1
640
====================================================================
方法二
def operation(value1,*value2):
list1 = list(value2)
first_value = list1[0]
for x in list1[1:]:
first_value = eval('%d %s %d' % (first_value,value1,x))
print(first_value)
operation('+',1,2)
operation('*',2,3,4,5)
结果:
3
120