1.编写一个函数,求1+2+3+...+N
def my_sum(*numbers):
print('number is ', numbers)
sum1 = 0
for item in numbers:
sum1 += item
print('sum is :', sum1)
my_sum(1, 2, 3, 4, 5, 6, 7)
输出:
number is (1, 2, 3, 4, 5, 6, 7)
sum is : 28
2.编写一个函数,求多个数中的最大值
def my_max(*numbers):
print('number is', numbers)
return max(numbers)
print(my_max(1, 2, 8, 4, 5))
输出:
number is (1, 2, 8, 4, 5)
最大值为: 8
3.编写一一个函数,实现摇色子的功能,打印n个色子的点数和
import random
n = int(input('你需要几个骰子的点数和?'))
def dianshuhe(M):
sum1 = 0
for m in range(1, M + 1):
i = random.randint(1, 6)
sum1 += i
print('骰子点数的和为%d' % sum1)
dianshuhe(n)
输出:
你需要几个骰子的点数和?3
骰子点数的和为9
- 编写一个函数,交换指定字典的key和value。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def jiaohuan(dict):
print(dict1)
dict2 = {}
for n in dict:
m = dict[n]
dict2[m] = n
print(dict2)
dict1 = {34: 12, 98: 23, 90: 32, 'a': 56}
jiaohuan(dict1)
输出结果:
{34: 12, 98: 23, 90: 32, 'a': 56}
{12: 34, 23: 98, 32: 90, 56: 'a'}
- 编写一个函数,三个数中的最大值
def max_num(a,b,c):
if a > b:
if a > c:
return a
else:
return c
else:
if b > c:
return b
print("这三个数最大值是:%d" % max_num(2,34,13))
输出结果:
34
6.编写-一个函数, 提取指定字符串中的所有的字母,然后拼接在一起后打印出来\n
"例如: ' 12a&bc12d--' --->打印'abcd'
def atoZ(one_str):
new_str = ''
for x in one_str:
if 'a' <= x <= 'z' or 'A' <= x <= 'Z':
new_str = new_str + x
print(new_str)
atoZ('12a&bc12d--')
输出:
abcd
7.写一个函数,求多个数的平均值
def ly_mean(*num):
sum1 = 0
for n in num:
sum1 += n
print('平均值为%d' % (sum1 // len(num)))
ly_mean(23, 54, 98, 89)
输出:
平均值为66
8.写一个函数,默认求10的阶层,也可以求其他数的阶层
def ly_factorial(n = 10):
sum1 = 1
for i in range(1, n+1):
sum1 *= i
print('这个数的阶乘为%d' % sum1)
ly_factorial(5)
输出:
120
9.写一个函数,可以对多个数进行不同的运算
例如: operation('+', 1,2,3) --->求1+2+3的结果
operation( '-',10,9) --->求10-9的结果
operation( '',2,4,8,10) --->求24* 8* 10的结构
def operation(flag, *nums):
num1 = 1
if flag == '+':
for num in nums:
print(num)
return sum(num)
elif flag == '-':
count = 1
for num in nums:
print(num)
for x in num:
while count == 1:
num1 = x
count += 1
num1 -= x
return num1
elif flag == '*':
for num in nums:
print(num)
for x in num:
num1 *= x
return num1
elif flag == '/':
count = 1
for num in nums:
print(num)
for x in num:
num1 /= x
return num1
else:
print('输入的运算符有误')
list1 = [10, 3, 5, 7, 9]
flag = input('输入要进行的运算(+,-,*,/):')
print(operation(flag, list1))
输出:
输入要进行的运算(+,-,*,/):+
[10, 3, 5, 7, 9]
34
网友评论