- 编写一个函数,求1+2+3+...+N
def sum_n(n):
sum1 = 0
for i in range(1,n+1):
sum1 += i
print(sum1)
sum_n(20)
- 编写一个函数,求多个数中的最大值
def max_n(*nums):
max1 = 0
for num in nums:
if num > max1:
max1 = num
print(max1)
max_n(100,88,108,45,-12)
- 编写一个函数,实现摇骰子的功能,打印n个骰子的点数和
import random
def dice(n):
sum1 = 0
for x in range(0,n):
num3 = random.randint(1,6)
sum1 += num3
print(num3)
return sum1
print(dice(3))
- 编写一个函数,交换指定字典的key和value。
如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
dict1 = {'a':1,'b':2,'c':3,'d':4}
def exchange(dicts):
for num in dicts.copy():
middle = dicts[num]
dicts[num] = num
dicts[middle] = dicts.pop(num)
new_dict = dicts
return new_dict
print(exchange(dict1))
- 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
如:'12a&bc12d--' ---> 打印'abcd'
list1 = []
for x in str1:
if x.isalpha():
list1.append(x)
new_str = str(list1)
print(new_str)
return new_str
print(get_letter('12abc12d'))
- 写一个函数,求多个数的平均值
def average_n(*nums):
print(nums)
sum3 = 0
for i in nums:
sum3 += i
average = sum3/len(nums)
return average
print(average_n(60,66,88,78))
- 写一个函数,默认求10的阶层,也可以求其他数的阶层
def jie_cheng(n=10):
sum1 = 1
for x in range(1,n+1):
sum1 *= x
return sum1
print(jie_cheng(8))
- 写一个函数,可以对多个数进行不同的运算
如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果 operation('-', 10, 9) ---> 求 10-9的结果 operation('', 2, 4, 8, 10) ---> 求 24810的结构
def operation(symbol,*num6):
if symbol == '+':
sum6 = 0
for num in num6:
sum6 += num
elif symbol == '-':
sum6 = 2 * num6[0]
for num in num6:
sum6 -= num
elif symbol == '*':
sum6 = 1
for num in num6:
sum6 *= num
return sum6
print(operation('-',10,9))
9.写一个函数,求指定列表中,指定的元素的个数
def list_num(list1, element):
num = list1.count( element)
return num
print(list_num([1,3,8,9,9,9,12,49],9))
10.写一个函数,获取指定列表中指定元素对应的下标(如果有多个,一起返回)
def list_id(list3, *elements):
list9 = []
for element in elements:
id1 = list3.index(element)
list9.append(id1)
return list9
print(list_id([1,8,9,5,],1))
网友评论