1. 编写⼀个函数,求1+2+3+...+N
答案:
def sum_n(n):
sum1 = 0
for i in range(n+1):
sum1 += i
print(sum1)
sum_n(3)
2. 编写⼀个函数,求多个数中的最⼤值
答案:
import random
def n_num_max(n):
num1 = []
for i in range(n):
num = random.randint(200,500)
num1.append(num)
max_num = max(num1)
print(num1)
print(max_num)
n_num_max(10)
3. 编写⼀个函数,实现摇⾊⼦的功能,打印n个⾊⼦的点数和
答案:
import random
def roll_the_dice(n):
sum1 = 0
for i in range(n):
num = random.randint(1,6)
sum1 += num
print(num)
print(sum1)
roll_the_dice(2)
4. 编写⼀个函数,交换指定字典的key和value。
答案:
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def exchage_key_and_value():
dict1 = {'a': 1, 'b': 2, 'c': 3}
aa = list(dict1.keys())
bb = list(dict1.values())
print(aa)
print(bb)
aaaa = []
for index in range(len(bb)):
aaa = []
aaa.append(bb[index])
aaa.append(aa[index])
aaaa.append(aaa)
aaaa = dict(aaaa)
print(aaaa)
5. 编写⼀个函数,三个数中的最⼤值
答案:
def max_num1_num2_num2(num1,num2,num3):
max_num = max(num1,num2,num3)
print(max_num)
max_num1_num2_num2(1,2,3)
6. 编写⼀个函数,提取指定字符串中的所有的字⺟,然后拼接在⼀起
后打印出来
例如:'12a&bc12d--' ---> 打印'abcd'
答案:
def find_zimu():
import string
import random
a =""
for i in range(6):
str1 = string.ascii_letters
str11 = random.choice(str1)
a += str11
num = random.randint(20, 50)
a += str(num)
new_str = a
print(a)
new_new_str = ' '
for item in new_str:
if item.isalpha():
new_new_str += item
print(new_new_str)
find_zimu()
7. 写⼀个函数,求多个数的平均值
答案:
n = int(input("你想求几个数的平均值:"))
import random
def many_num_sum(n):
a = []
for i in range(n):
b = random.randint(1,1000)
a.append(b)
print(a)
print(sum(a)/len(a))
many_num_sum(n)
8. 写⼀个函数,默认求10的阶层,也可以求其他数的阶层
答案:
def random_num_jiecheng(num):
print(num)
cj = 1
for i in range(1,num+1):
cj *= i
print(cj)
import random
random_num_jiecheng(num = random.randint(1,10))
9. 写⼀个函数,可以对多个数进⾏不同的运算
例如:
operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('', 2, 4, 8, 10) ---> 求 24810的结构
答案:
def differernt_function():
sum = 0
for i in range(0,11):
sum += i
print("和为",sum)
num1 = int(input("输入被减数:"))
num2 = int(input("请输入减数:"))
cha = num1 - num2
print("差",cha)
cj = 1
for j in range(0,11,2):
cj *= j
print("偶数乘积",cj)
differernt_function()