- 编写一个函数,求1+2+3+...+N
def my_sum(n):
sum1 = 0
for i in range(1,n+1):
sum1 += i
return sum1
print(my_sum(100))
- 编写一个函数,求多个数中的最大值
def my_max(*nums):
max1 = nums[0]
for item in nums:
if item > max1:
max1 =item
return max1
print(my_max(13,24,46,77,90))
from random import randint
- 编写一个函数,实现摇骰子的功能,打印n个骰子的点数和
def play_dict(n):
sum1 = 0
for _ in range(n):
num = randint(2,6)
print(num)
sum1 += num
return sum1
print(play_dict(4))
- 编写一个函数,交换指定字典的key和value。
如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def change_key_value(dict1:dict):
for key in dict1.copy():
value = dict1[key]
del dict1[key]
dict1[value] = key
dict2 = {'a':1, 'b':2, 'c':3}
change_key_value(dict2)
print(dict2)
- 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
如:'12a&bc12d--' ---> 打印'abcd'
def connect(str1:str):
str2 = ''
for char in str1:
if char.isalpha():
str2 +=char
return str2
print(connect('12a&bc12d'))
- 写一个函数,求多个数的平均值
def my_mean(*nums):
return sum (nums) /len (nums)
print(my_mean(1,3,5,7))
- 写一个函数,默认求10的阶层,也可以求其他数的阶层
def my_factorial(n=10):
sum1 = 1
for i in range(1,n+1):
sum1 *= i
return sum1
print(my_factorial(5))
print(my_factorial())
- 写一个函数,可以对多个数进行不同的运算
如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果 operation('-', 10, 9) ---> 求 10-9的结果 operation('', 2, 4, 8, 10) ---> 求 24810的结构
def my_operation(operator,*nums):
if operator == '+':
sum1 = 0
for num in nums:
sum1 +=num
return sum1
elif operator == '-':
sum1 =nums[0]
for index in range(1,len(nums)):
sum1 -=nums[index]
return sum1
elif operator == '*':
sum1 = 1
for num in nums:
sum1 *= num
return sum1
print(my_operation('+',1,2,3,4))
print(my_operation('-',1,2,3,4))
print(my_operation('*',1,2,3,4))
9.写一个函数,求指定列表中,指定的元素的个数
def my_count(list1:list,item):
count = 0
for i in list1:
if i == item:
count == 1
return count
print(my_count([1,2,3,4,7],3))
10.写一个函数,获取指定列表中指定元素对应的下标(如果有多个,一起返回)
def my_index(list1, item):
indexs = []
for index in range(len(list1)):
x =list1[index]
if x == item:
indexs.append(index)
return indexs
print(my_index([1,2,4,7,1,34],1)
网友评论