import random
1. 编写一个函数,求1+2+3+...+N
def my_sum(n1):
sum1 = 0
for i in range(1,n1+1):
sum1 += i
return sum1
k = my_sum(5)
print(k,"\n~~~~~~~~~~~~~~~~~~~~~")
2. 编写一个函数,求多个数中的最大值
def my_max(*n2):
num_max = 0
for i in n2:
if num_max < i:
num_max = i
return num_max
j = my_max(12,3,44)
print(j,"\n~~~~~~~~~~~~~~~~~~~~~")
3. 编写一个函数,实现摇骰子的功能,打印n个骰子的点数和
def sum_of_touzi(n):
sum2 = 0
for i in range(0,n):
x = random.randint(1, 6)
print(x)
sum2 += x
return sum2
l = sum_of_touzi(4)
print(l,'\n~~~~~~~~~~~~~~~~~~~~~~~~~~')
4. 编写一个函数,交换指定字典的key和value。
如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def change_key_value(n):
list1 = []
dict1 = {}
list1 = n.items()
for t in list1:
x,y = t
x,y = y,x
dict1[x] = y
return dict1
m = change_key_value({'a':5, 'b':8, 'c':9})
print(m,'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
5. 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
如:'12a&bc12d--' ---> 打印'abcd'
def get_letter(n):
str1 =''
for letter1 in n:
if 'a'<= letter1 <= 'z'or 'A' <= letter1 <='Z':
str1 += letter1
print(str1)
get_letter("123nl1kjn3123jn1l")
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
6. 写一个函数,求多个数的平均值
def my_average(*n):
sum = 0
for i in n:
sum += i
average1 = sum/len(n)
return average1
a = my_average(1,2,3,7,8,9)
print(a,"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
7. 写一个函数,默认求10的阶层,也可以求其他数的阶层
def jiecheng(n = 10):
num = 1
for i in range(1,n+1):
num *= i
return num
b = jiecheng()
c = jiecheng(5)
print(b,c,'\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
8. 写一个函数,可以对多个数进行不同的运算
如:
operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('', 2, 4, 8, 10) ---> 求 24810的结构
def my_math(*n):
if n[0] == '+':
num = n[1]
for i in range(2, len(n)):
num += n[i]
if n[0] =='-':
num = n[1]
for i in range(2, len(n)):
num -= n[i]
if n[0] =='*':
num = n[1]
for i in range(2, len(n)):
num *= n[i]
if n[0] == '/':
num = n[1]
for i in range(2, len(n)):
num /= n[i]
return num
d = my_math('+',1,2,3,4,5)
e = my_math('-',10,6,7)
f = my_math('*',4,5,6)
p = my_math('/',9,6)
print(d)
print(e)
print(f)
print(p)
9.写一个函数,求指定列表中,指定的元素的个数
m为指定列表,n为指定元素
def my_func(m,n):
i = 0
for x in m:
if x == n:
i += 1
return i
q = my_func([1,2,3,4,5,1,3,4,5,3,45],3)
print(q)
10.写一个函数,获取指定列表中指定元素对应的下标(如果有多个,一起返回)
m为指定列表,n为指定元素
def get_xiabiao(m, n):
list = []
for i in range(len(m)):
if m[i] == n:
list.append(i)
return list
r = get_xiabiao([1, 2, 3, 4, 5, 1, 3, 4, 5, 3, 45], 3)
print(r)