- 編寫?個函數(shù)渗饮,求1+2+3+...+N
def lei_jao(n):
sum1 = 0
for x in range(1,n+1):
sum1 += x
print(sum1)
- 編寫?個函數(shù)这橙,求多個數(shù)中的最?值
def print_max(list1):
print(max(list1))
- 編寫?個函數(shù)革为,實現(xiàn)搖??的功能拔稳,打印n個??的點數(shù)和
import random
def dianshu_sum(n):
x =0
list1=[]
while x < n:
num = random.randint(1, 7)
list1.append(num)
x+=1
print(sum(list1),list1)
dianshu_sum(8)
點數(shù)是: 31
[6, 2, 4, 3, 7, 2, 1, 6]
- 編寫?個函數(shù)灭必,交換指定字典的key和value。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
dict2 = {'a': 1, 'b': 2, 'c': 3}
def exchange_key_value(dict1):
dict3 = {}
for key in dict1:
dict3.update({dict1[key]:key})
print(dict3)
exchange_key_value(dict2)
{1: 'a', 2: 'b', 3: 'c'}
- 編寫?個函數(shù)琢蛤,三個數(shù)中的最?值
def num_max(a,b,c):
num = max(a,b,c)
print(num)
num_max(9,8,7)
9
- 編寫?個函數(shù)懂诗,提取指定字符串中的字?蜂嗽,然后拼接在?起后打印出來
例如:'12a&bc12d' ---> 打印'abcd'
def word(str1):
str2 = ''
for x in range(len(str1)):
if ('a'<= str1[x] <='z')or ('A'<= str1[x]<='Z'):
str2 += str1[x]
print(str2)
word('abc123AD')
abcAD
- 寫?個函數(shù),求多個數(shù)的平均值
def average_num(num):
sum1 = 0
for x in range(len(num)):
sum1 = sum1 + num[x]
sum2 = sum1 / len(num)
print('%.2f'%sum2)
average_num([10,20,30,40])
25.0
- 寫?個函數(shù)殃恒,默認求10的階層植旧,也可以求其他數(shù)的階層
def jiecheng(num = 10):
sum1 =1
for x in range(1,num):
sum1 = sum1 * x
print(sum1)
jiecheng(4)
jiecheng(4)
jiecheng()
6
362880
- 寫?個函數(shù)辱揭,可以對多個數(shù)進?不同的運算
例如: operation('+', 1, 2, 3) ---> 求 1+2+3的結(jié)果
operation('-', 10, 9) ---> 求 10-9的結(jié)果
operation('', 2, 4, 8, 10) ---> 求 24810的結(jié)構(gòu)
def yunsuan(tuple1):
sum1 = 1
flag ,*num = tuple1
if flag == '+':
sum1 = sum(num)
elif flag == '*':
for x in range(len(num)):
sum1 = sum1*num[x]
print(sum1 )
yunsuan(('+',1,2,3,4))
yunsuan(('*',1,2,3,4))
10
24