- 编写一个函数,求1+2+3+...+N
def sum1(N):
sum = 0
for x in range(1,N+1):
sum+=x
print(sum)
sum1(10)
- 编写一个函数,求多个数中的最大值
def max_num(*arg):
return max(arg)
max_num(12,33,24,45)
- 编写一个函数,实现摇骰子的功能,打印n个骰子的点数和
import random
def my_sum(n):
count = 0
for _ in range(n):
point = random.randint(1, 6)
count += point
return count
print(my_sum(5))
- 编写一个函数,交换指定字典的key和value。
如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
dict1 = {'a':1, 'b':2, 'c':3}
def exchange(dict1:dict):
new_dict = {}
for i in dict1:
new_dict[dict1[i]] = i
return new_dict
print(exchange(dict1))
- 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
如:'12a&bc12d--' ---> 打印'abcd'
def zimu(str1:str):
new_str = ""
for i in range(len(str1)):
if "a" <= str1[i]<= "z" or "A" <= str1[i] <= "Z":
new_str+=str1[i]
print(new_str)
zimu("12a&bc12d--")
- 写一个函数,求多个数的平均值
def mean(*n):
sum1 = sum(n)
means = sum1/len(n)
return means
print("平均数是:%.2f" % means)
print(mean(1,2,4,10,29))
- 写一个函数,默认求10的阶层,也可以求其他数的阶层
def product(n):
sum = 1
for x in range(1,n+1):
sum *= x
return sum
re=product(10)
print(re)
- 写一个函数,可以对多个数进行不同的运算
如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果 operation('-', 10, 9) ---> 求 10-9的结果 operation('', 2, 4, 8, 10) ---> 求 24810的结构
def calculate(oper, *nums):
sum1 = nums[0]
if oper == '+':
for num in nums[1:]:
sum1 += num
elif oper == '-':
for num in nums[1:]:
sum1 -= num
elif oper == '*':
for num in nums[1:]:
sum1 *= num
elif oper == '/':
for num in nums[1:]:
sum1 /= num
return sum1
num = calculate('+', 1, 2, 3)
print(num) # 6
num2 = calculate('-', 10, 9)
print(num2) # 1
num3 = calculate('*', 2, 4, 8, 10)
print(num3)
9.写一个函数,求指定列表中,指定的元素的个数
def count_num(any_list,any_item):
sum1 = 0
for item in any_list:
if item == any_item:
sum1 += 1
return sum1
list1 = [1, 3, 1, 4, 5, 2, 0]
num = count_num(list1, 1)
print(num) # 2
10.写一个函数,获取指定列表中指定元素对应的下标(如果有多个,一起返回)
def get_index(any_list, any_item):
index_list = []
index = 0
while index < len(any_list):
if any_list[index] == any_item:
index_list.append(index)
index += 1
return index_list
list1 = [1, 3, 1, 4, 5, 2, 0]
index_list1 = get_index(list1,1)
print(index_list1) # [0, 2]
网友评论