- 編寫(xiě)?個(gè)函數(shù),求1+2+3+...+N
def my_sum1(n):
sum1 = 0
for x in range(n+1):
sum1 += x
print(sum1)
my_sum1(3)
- 編寫(xiě)?個(gè)函數(shù),求多個(gè)數(shù)中的最?值
def num_max(*num):
print(max(num))
num_max(1, 2, 3)
- 編寫(xiě)?個(gè)函數(shù)腹缩,實(shí)現(xiàn)搖??的功能株依,打印n個(gè)??的點(diǎn)數(shù)和
def play_dice(n):
import random
sum = 0
for _ in range(n):
num = random.randint(1, 6)
sum += num
print(sum)
play_dice(3)
- 編寫(xiě)?個(gè)函數(shù),交換指定字典的key和value胯陋。
例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def dict_exchange_key_value(**dict1):
dict2 = {}
for x in dict1:
dict2[dict1[x]] = x
dict1 = dict2
print(dict1)
dict_exchange_key_value(a=1, b= 2, c= 3)
- 編寫(xiě)?個(gè)函數(shù),三個(gè)數(shù)中的最?值
def num_max(*num):
print(max(num))
num_max(1, 2, 3)
- 編寫(xiě)?個(gè)函數(shù),提取指定字符串中的所有的字?卜朗,然后拼接在?起后打印出來(lái)
例如:'12a&bc12d--' ---> 打印'abcd'
def extract_str_letter(str1):
str2 = ''
for x in str1:
if x.isalpha():
str2 += x
print(str2)
extract_str_letter('abcd1234')
- 寫(xiě)?個(gè)函數(shù),求多個(gè)數(shù)的平均值
def more_num_average(*num):
print(sum(num)/len(num))
more_num_average(1, 2, 3)
- 寫(xiě)?個(gè)函數(shù)咕村,默認(rèn)求10的階層场钉,也可以求其他數(shù)的階層
def ten_factorial():
ten_factorial_value = 1
num_factorial_value = 1
for x in range(1, 11):
ten_factorial_value *= x
print(ten_factorial_value)
num = input('如果要求其他數(shù)的階乘,請(qǐng)輸入這個(gè)數(shù)懈涛;否則輸入 end 9渫颉:')
if num.isdigit():
for x in range(1, int(num)+1):
num_factorial_value *= x
print(num_factorial_value)
ten_factorial()
- 寫(xiě)?個(gè)函數(shù),可以對(duì)多個(gè)數(shù)進(jìn)?不同的運(yùn)算
例如: operation('+', 1, 2, 3) ---> 求 1+2+3的結(jié)果
operation('-', 10, 9) ---> 求 10-9的結(jié)果
operation('', 2, 4, 8, 10) ---> 求 24810的結(jié)構(gòu)
def more_num_operation(operation, *num):
if operation[0] == '+':
print(sum(num))
if operation[0] == '-':
result = num[0]
for x in range(1, len(num)):
result -= num[x]
print(result)
if operation[0] == '*':
result = 1
for x in num:
result *= x
print(result)
more_num_operation('+', 1,2,3)