- 编写⼀个函数,求1+2+3+...+N
def my_sum(n):
sum1 = 0
for i in range(0, n + 1):
sum1 += i
return sum1
print(my_sum(100))
- 编写⼀个函数,求多个数中的最⼤值
def my_max(list1=[]):
max1 = max(list1)
return max1
print(my_max(list1=[1, 2, 3, 4, 88, 99, 10]))
- 编写⼀个函数,实现摇⾊⼦的功能,打印n个⾊⼦的点数和
import random
def my_sum1(n):
rand = 0
for i in range(n):
rand += random.randint(1, 7)
return rand
print(my_sum1(5))
- 编写⼀个函数,交换指定字典的key和value。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def exchange(dict = {}):
dict2 = {}
for key in dict:
dict2.update({dict[key]: key})
return dict2
print(exchange(dict = {'a':1, 'b':2, 'c':3}))
- 编写⼀个函数,三个数中的最⼤值
def my_max(list):
return max(list)
print(my_max([1, 2, 3]))
- 编写⼀个函数,提取指定字符串中的所有的字⺟,然后拼接在⼀起后打印出来
例如:'12a&bc12d--' ---> 打印'abcd'
def alpha(str1):
str2 = ''
for i in range(len(str1)):
if ('a' <= str1[i] <= 'z') or ('A' <= str1[i] <= 'Z'):
print((str2 + str1[i]), end="")
alpha('dsfds445sdf')
- 写⼀个函数,求多个数的平均值
def ave(list):
sum = 0
for i in list:
sum += i
return sum / len(list)
print(ave([1,2,3,4,5,6,7,8,9,0]))
- 写⼀个函数,默认求10的阶层,也可以求其他数的阶层
def factorial(n=10):
sum = 1
for i in range(1, n + 1):
sum *= i
return sum
print(factorial())
- 写⼀个函数,可以对多个数进⾏不同的运算
例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('', 2, 4, 8, 10) ---> 求 24810的结构
def more_operation(str, list=[]):
sum1 = 0
sum2 = 0
sum3 = 1
if str == '+':
for i in list:
sum1 += i
return sum1
elif str == '-':
for i in list:
sum2 -= i
return sum2 + list[0] * 2
elif str == '*':
for i in list:
sum3 *= i
return sum3
elif str == '/':
for i in list:
sum3 /= i
return sum3 * (list[0] ** 2)
list1 = [10, 20, 30, 50]
print(more_operation('/', list1))
网友评论