- 編寫一個函數(shù)参萄,求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的值:')))
- 編寫一個函數(shù)讹挎,求多個數(shù)中的最大值
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]))
- 編寫一個函數(shù)吆玖,實現(xiàn)搖骰子的功能马篮,打印n個骰子的點數(shù)和
def shaizi():
import random
x = random.randint(1,6)
return x
sums = 0
n = int(input('請輸入擲骰子次數(shù):'))
for i in range(1,n+1):
num = shaizi()
sums += num
print(sums)
- 編寫一個函數(shù),交換指定字典的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)
- 編寫一個函數(shù),提取指定字符串中的所有的字母怎顾,然后拼接在一起后打印出來
如:'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'))
- 寫一個函數(shù)漱贱,求多個數(shù)的平均值
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]))
- 寫一個函數(shù),默認(rèn)求10的階層募强,也可以求其他數(shù)的階層
def fac(y = 10):
num1 = 1
for i in range(1,y+1):
num1 *= i
return num1
print(fac(1))
- 寫一個函數(shù)崇摄,可以對多個數(shù)進行不同的運算
如: operation('+', 1, 2, 3) ---> 求 1+2+3的結(jié)果 operation('-', 10, 9) ---> 求 10-9的結(jié)果 operation('', 2, 4, 8, 10) ---> 求 24810的結(jié)構(gòu)
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.寫一個函數(shù),求指定列表中逐抑,指定的元素的個數(shù)
# 求列表中(2,1,3)的個數(shù)
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.寫一個函數(shù),獲取指定列表中指定元素對應(yīng)的下標(biāo)(如果有多個进每,一起返回)
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))