- 编写一个函数,求1+2+3+...+N
def func(n):
sum1 = 0
for num in range(n+1):
sum1 += num
return sum1
print(func(5))
- 编写一个函数,求多个数中的最大值
def func(*args):
num1 = 0
for num in args:
if num > num1:
num1 = num
return num1
print(func(5, 6, 24, 1, -2))
- 编写一个函数,实现摇色子的功能,打印n个色子的点数和
import random
def func(n):
dice_num = 0
sum = 0
for x in range(1, n+1):
dice_num += 1
while dice_num > 0:
point = random.randint(1, 6)
sum += point
dice_num -= 1
return sum
print(func(1))
- 编写一个函数,交换指定字典的key和value。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def func(dict1):
dict2 = {}
for key in dict1:
dict2[dict1[key]] = key
return dict2
dict1 = {"a": 1, "b": 2, "c": 3}
print(func(dict1))
- 编写一个函数,三个数中的最大值
def func(a, b, c):
return max(a, b, c)
print(func(1, 12, 2))
- 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
例如:'12a&bc12d--' ---> 打印'abcd'
def func(str):
new_str = ''
for item in str:
if 65<=ord(item)<=90 or 97<=ord(item)<=122:
new_str += item
return new_str
print(func('12a&bc12d'))
- 写一个函数,求多个数的平均值
def func(*args):
sum1 = 0
for num1 in args:
sum1 += num1
print(sum1)
return sum1/len(args)
print(func(1, 2, 3, 4, 5))
- 写一个函数,默认求10的阶层,也可以求其他数的阶层
def func(n=10):
sum1 = 1
for num1 in range(1,n+1):
sum1 *= num1
return sum1
print(func())
- 写一个函数,可以对多个数进行不同的运算
`例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('', 2, 4, 8, 10) ---> 求 24810的结构
def operation(*args):
sign, *num = args
if sign == '+':
sum = num[0]
for x in range(1,len(num)):
sum += num[x]
elif sign == '-':
sum = num[0]
for x in range(1, len(num)):
sum -= num[x]
elif sign == '*':
sum = num[0]
for x in range(1, len(num)):
sum *= num[x]
elif sign == '/':
sum = num[0]
for x in range(1, len(num)):
sum /= num[x]
return sum
print(operation('+', 1, 2, 3))
print(operation('-', 10, 9))
print(operation('*', 2, 4, 8, 10))
网友评论