1编写一个函数,求1+2+3+...+n
def my_sum(n):
sum1 = 0
for i in range(n):
sum1 += i
print(sum1)
my_sum(10)
-->
45
2编写一个函数,求多个数中的最大值
def my_max(*number):
max = number[0]
for item in number:
if max>item:
pass
else:
max=item
print('最大值为%d'%max)
my_max(1,3,23,4,4323,32,4,343)
-->
最大值为4323
3编写一个函数,实现摇骰子功能,打印N个筛子的点数和
import random
def my_sum(n):
sum = 0
for i in range(n):
x = random.randint(1,7)
sum += x
print('%d次骰子的点数和为%d'%(n,sum))
my_sum(5)
-->
5次骰子的点数和为24
4编写一个函数,交换指定字典的key和value(例如 {‘a’:1,'b':2,'c':3}-->{'1':a,'2':b,'3':c})
def exchange(dict):
print('转换前的字典为:')
print(dict)
dict1 = {}
for key in dict.keys():
dict1.update({dict[key]:key})
print('转换后的字典为:')
print(dict1)
dict2 ={'a':1,'b':2,'c':3}
exchange(dict2)
-->
转换前的字典为:
{'a': 1, 'b': 2, 'c': 3}
转换后的字典为:
{1: 'a', 2: 'b', 3: 'c'}
5编写一个函数,求三个数中的最大值
def my_max(a,b,c):
max = 0
if a>=b:
max = a
if max < c:
max = c
else:
max =b
if max < c:
max = c
print('最大值为:%d'%max)
my_max(1,19,45)
-->
最大值为:45
6编写一个函数,提取指定字符串中的所有字母,然后拼接在一起后打印出来('21fda^dad'-->'fdadad')
def abs(str1):
str2 = ''
for item in str1:
if 'a'<=item <= 'z' or 'A'<item<'Z':
str2 += item
print(str2)
str1 = '21fda^dad'
abs(str1)
-->
dadad
7.写一个函数,求多个数的平均值
def my_avg(*number):
count = 0
sum = 0
for item in number:
sum +=item
count +=1
total = (sum/count)
print('平均是为:%.2f'%total)
my_avg(1,4,6,8,9)
-->
平均是为:5.60
8.写一个函数,默认求10的阶层,也可以求其他数的阶层
ef actorial(n=10):
total =1
for i in range(1,n+1):
total *= i
print('%d的阶乘为%d'%(n,total))
actorial(5)
actorial()
-->
5的阶乘为120
10的阶乘为3628800
9.写一个函数,可以对多个数进行不同的运算
例如: operation('+', 1,2,3) --->求1+2+3的结果
operation( '-',10,9) --->求10-9的结果
operation( '',2,4,8,10) --->求24* 8* 10的结构
def operation(per,*number):
if per == '+':
total=0
for items in number:
total +=items
print('结果为:%d'%total)
if per == '-':
number1 = number[0]
for i in range(1,len(number)):
number1 = number1 - number[i]
print('结果为:%d'%number1)
if per == '*':
total = 1
for item in number:
total *= item
print('结果为:%d'%total)
operation('+',1,2,3,4)
operation('-',1,2,3,4)
operation('*',1,2,3,4)
-->
结果为:10
结果为:-8
结果为:24
网友评论