- 编写一个函数,求1+2+3+...+N
def W_sum(n):
sums = 0
for i in range(n+1):
sums += i
print(sums)
W_sum(n = int(input('请输入n的值:')))
- 编写一个函数,求多个数中的最大值
def W_max(list1):
max1 = 0
for num in list1:
if max1 < num:
max1 = num
return max1
print(W_max([1,5,8,55,2,6]))
- 编写一个函数,实现摇骰子的功能,打印n个骰子的点数和
def shaizi():
import random
x = random.randint(1,6)
return x
sums = 0
n = int(input('请输入掷骰子次数:'))
for i in range(1,n+1):
num = shaizi()
sums += num
print(sums)
- 编写一个函数,交换指定字典的key和value。
如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def exchange(x,y):
t = x
y = t
x = y
dict1 = {'a':1, 'b':2, 'c':3}
for x in dict1:
exchange(x,dict1[x])
print(dict1)
- 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
如:'12a&bc12d--' ---> 打印'abcd'
def tiqu(str1):
str2 = ''
for x in str1:
if 'a' <= x <= 'z' or 'A' <= x <= 'Z':
str2 += x
return str2
print(tiqu('sjhu1988j'))
- 写一个函数,求多个数的平均值
def ave(list1):
sums = 0
for num in list1:
sums += num
mean_value = sums / int(len(list1))
return mean_value
print(ave([1,2,3]))
- 写一个函数,默认求10的阶层,也可以求其他数的阶层
def fac(y = 10):
num1 = 1
for i in range(1,y+1):
num1 *= i
return num1
print(fac(1))
- 写一个函数,可以对多个数进行不同的运算
如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果 operation('-', 10, 9) ---> 求 10-9的结果 operation('', 2, 4, 8, 10) ---> 求 24810的结构
def operation(operator,*n):
result = n[0]
for x in range(1,len(n)):
if operator == '+':
result += n[x]
elif operator == '-':
result -= n[x]
elif operator == '*':
result *= n[x]
else:
result /= n[x]
return result
print(operation('/',1,2,3))
9.写一个函数,求指定列表中,指定的元素的个数
# 求列表中(2,1,3)的个数
def W_count(list1):
num1 = 0
for x in list1:
if x == (2,1,3):
num1 += 1
return num1
list2 = [1,2,(2,1,3),(2,1,3),(2,1,3)]
print(W_count(list2))
10.写一个函数,获取指定列表中指定元素对应的下标(如果有多个,一起返回)
def sub(list1):
sub1 = []
for x in range(len(list1)):
if list1[x] == (2,1,3):
sub1.append(x)
return sub1
list2 = [1,2,(2,1,3),(2,1,3),(2,1,3)]
print(sub(list2))