1.编写一个函数,求1+2+3+...+N
- 实现程序
def get_sum(n):
sum1 = 0
for i in range(1, n + 1):
sum1 += i
return sum1
print(get_sum(100))
Outout:
5050
2.编写一个函数,求多个数中的最大值
- 实现程序
def get_max(*numbers):
max_number = 0
for number in numbers:
if max_number > number:
max_number = max_number
else:
max_number = number
return max_number
print(get_max(15, 10, 60))
Output:
60
3.编写一个函数,实现摇色子的功能,打印n个色子的点数和
- 实现程序
def get_point_sum(n):
point_sum = 0
for _ in range(1, n + 1):
point_number = randint(1, 7) # 色子产生点数
print(point_number, end=' ') # 将每次产生的点数打印出来
point_sum += point_number # 求和点数
return point_sum
print('\n', get_point_sum(4))
Output:
4 6 2 3
15
4.编写一个函数,交换指定字典的key和value。
- 实现程序
def exchange_key_and_value(dic):
dic = dict((v, k) for k, v in dic.items()) # 将字典转换为元组后交换每个元组元素值,再将元组转换成字典
return dic
dict_demo = {'name': '1', 'age': 23}
print(exchange_key_and_value(dict_demo))
Output:
{'1': 'name', 23: 'age'}
5.编写一个函数,求三个数中的最大值
- 实现程序
def get_max_in_three_numbers(a, b, c):
max_number = a
if a > b:
max_number = a
if max_number > c:
max_number = max_number
else:
max_number = c
else:
max_number = b
if max_number > c:
max_number = max_number
else:
max_number = c
return max_number
print(get_max_in_three_numbers(9, 5, 46))
6.编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起打印出来
- 实现程序
def get_all_letters(string):
all_letters = ''
for char in string:
if 'a' < char < 'z' or 'A' < char < 'Z':
all_letters += char
return all_letters
string = 'bcr72h dfy8g 8yfwfw 8 feh vy8qw'
print(get_all_letters(string))
Output:
bcrhdfygyfwfwfehvyqw
7.编写一个函数,求多个数的平均值
- 实现程序
def get_avg(*numbers):
number_sum = 0
for number in numbers:
number_sum += number
avg = number_sum / len(numbers)
return avg
print(get_avg(1, 6, 5))
Output:
4.0
8.编写一个函数,默认求10的阶乘,也可以求其他数的阶乘
- 实现程序
def get_factorial(n=10):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
print(get_factorial())
Output:
3628800
9.编写一个函数,可以对多个数进行不同的运算
- 实现程序
def operation(operator, *numbers):
mul_result = 1
add_result = 0
sub_result = 2 * numbers[0]
for number in numbers:
mul_result *= number
add_result += number
sub_result -= number
if operator == '*':
return mul_result
elif operator == '+':
return add_result
else:
return sub_result
print(operation('+', 1, 2, 3))
print(operation('-', 10, 9))
print(operation('*', 2, 4, 8, 10))
Output:
6
1
640