1. 编写一个函数,求1+2+3+...+N
def num1(N):
sum = 0
for num2 in range(1,N+1):
sum += num2
print(sum)
return sum
num1(10)
2. 编写一个函数,求多个数中的最大值
def max1(*nums):
print(max(nums))
return max(nums)
re = max1(1,2,3,4,5,6)
print(re)
3. 编写一个函数,实现摇骰子的功能,打印n个骰子的点数和
import random
或
from random import randint
def play_dice(n):
sum1 = 0
for _ in range(n):
num = randint(1, 6)
print(num)
sum1 += num
return sum1
print(play_dice(2))
4. 编写一个函数,交换指定字典的key和value。
def change_key_value(dict1:dict):
for key in dict1.copy():
# 通过key拿到值
value = dict1[key]
# 删除原来的键值对
del dict1[key]
# 将值作为key,键作为value,添加键值对
dict1[value] = key
copy: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
原:{ 1:'a', 2:'b', 3:'c', 4:'d' }
key = 'a' value=1 dict1[1]='a'
key = 'b' value=2 dict1[2]='b'
dict11 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
change_key_value(dict11)
print(dict11)
5. 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
如:'12a&bc12d--' ---> 打印'abcd'
def print_letter(str1):
new = ''
for letter in str1:
if letter.isalpha() == True:
new += letter
print(new)
return new
new1 = print_letter('12a&bc12d')
print(new1)
6. 写一个函数,求多个数的平均值
def mean1(*nums):
sum1 = 0
for num in nums:
sum1 += num
print(sum1/len(nums))
return sum1/len(nums)
mean2 = mean1(1,2,3,4,5,6)
print(mean2)
7. 写一个函数,默认求10的阶层,也可以求其他数的阶层
def jie_ceng(n):
num3 = 1
for num in range(1,n+1):
num3 *= num
print(num3)
return num3
jie_ceng1 = jie_ceng(10)
print(jie_ceng1)
8. 写一个函数,可以对多个数进行不同的运算
如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果 operation('-', 10, 9) ---> 求 10-9的结果 operation('', 2, 4, 8, 10) ---> 求 24810的结构
def operation(*tuple1):
frist_num = tuple1[0]
if frist_num == '+':
sum2 = 0
for index in range(1,len(tuple1)):
sum2 += tuple1[index]
return sum2
elif frist_num == '-':
sum2 = tuple1[1]
for index in range(2,len(tuple1)):
sum2 -= tuple1[index]
return sum2
elif frist_num == '*':
sum2 = 1
for index in range(1,len(tuple1)):
sum2 *= tuple1[index]
return sum2
operation1 = operation('*',2,4,8,10)
print(operation1)
9.写一个函数,求指定列表中,指定的元素的个数
def count1(list,num4):
number =list.count(num4)
print(number)
count1([1,2,3,4,5,6,6,6,66],6)
10.写一个函数,获取指定列表中指定元素对应的下标(如果有多个,一起返回)
def index1(list2,num1):
list3 = []
for index2 in range(0,len(list2)):
if list2[index2] == num1:
list3.append(index2)
return list3
index3 = index1([1,2,3,4,5,6,5,7,5],5)
print(index3)