- 编写⼀个函数,求1+2+3+...+N
def my_sum1(n):
sum1 = 0
for x in range(n+1):
sum1 += x
print(sum1)
my_sum1(3)
- 编写⼀个函数,求多个数中的最⼤值
def num_max(*num):
print(max(num))
num_max(1, 2, 3)
- 编写⼀个函数,实现摇⾊⼦的功能,打印n个⾊⼦的点数和
def play_dice(n):
import random
sum = 0
for _ in range(n):
num = random.randint(1, 6)
sum += num
print(sum)
play_dice(3)
- 编写⼀个函数,交换指定字典的key和value。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def dict_exchange_key_value(**dict1):
dict2 = {}
for x in dict1:
dict2[dict1[x]] = x
dict1 = dict2
print(dict1)
dict_exchange_key_value(a=1, b= 2, c= 3)
- 编写⼀个函数,三个数中的最⼤值
def num_max(*num):
print(max(num))
num_max(1, 2, 3)
- 编写⼀个函数,提取指定字符串中的所有的字⺟,然后拼接在⼀起后打印出来
例如:'12a&bc12d--' ---> 打印'abcd'
def extract_str_letter(str1):
str2 = ''
for x in str1:
if x.isalpha():
str2 += x
print(str2)
extract_str_letter('abcd1234')
- 写⼀个函数,求多个数的平均值
def more_num_average(*num):
print(sum(num)/len(num))
more_num_average(1, 2, 3)
- 写⼀个函数,默认求10的阶层,也可以求其他数的阶层
def ten_factorial():
ten_factorial_value = 1
num_factorial_value = 1
for x in range(1, 11):
ten_factorial_value *= x
print(ten_factorial_value)
num = input('如果要求其他数的阶乘,请输入这个数;否则输入 end !:')
if num.isdigit():
for x in range(1, int(num)+1):
num_factorial_value *= x
print(num_factorial_value)
ten_factorial()
- 写⼀个函数,可以对多个数进⾏不同的运算
例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('', 2, 4, 8, 10) ---> 求 24810的结构
def more_num_operation(operation, *num):
if operation[0] == '+':
print(sum(num))
if operation[0] == '-':
result = num[0]
for x in range(1, len(num)):
result -= num[x]
print(result)
if operation[0] == '*':
result = 1
for x in num:
result *= x
print(result)
more_num_operation('+', 1,2,3)