1.编写一个函数,求1+2+3+...+N
def sum1(num):
sum1 = 0
for i in range(0,num+1):
sum1 += i
print(sum1)
sum1(5)
15
Process finished with exit code 0
2.编写一个函数,求多个数中的最大值
def my_max(*num):
a = max(num)
print(a)
my_max(6,5,9,8,2)
9
Process finished with exit code 0
3.编写一个函数,实现摇色子的功能,打印n个色子的点数和
import random
def ysz():
sum1 = 0
nums = []#存储色子的点数
for i in range(3):#摇3次色子
num = random.randint(1,6)
nums.append(num)
sum1 += num
print(nums)
print(sum1)
ysz()
[3, 6, 6]
15
Process finished with exit code 0
4.编写一个函数,交换指定字典的key和value。
例如:{‘a’:1, ‘b’:2, ‘c’:3}--->{1:‘a’, 2:‘b’, 3:‘c’}
def exchange(dict1):
new_dict = {}
for key in dict1:
value = dict1.get(key)
new_dict[value] = key
print(new_dict)
exchange({'a':1,'b':2,'c':3})
{1: 'a', 2: 'b', 3: 'c'}
Process finished with exit code 0
5.编写一个函数,三个数中的最大值
def my_max(num1,num2,num3):
a = max(num1,num2,num3)
print(a)
my_max(8,22,3)
22
Process finished with exit code 0
6.编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
例如:'13as8(*&hj2d' ---> 打印'ashjd'
方法一:
def tq_str(str1):
for i in str1:
if i.isalpha():
print(i,end='')
tq_str('sa1ls231')
方法二:
def tq_str(str1):
a = ''
for i in str1:
if 'a' <= i <='z' or 'A'<= i <='Z':
a += str(i)
print(a)
tq_str('sa1ls231')
方法三:
def tq_str(str1):
for i in str1:
if 'a' <= i <='z' or 'A'<= i <='Z':
print(i,end='')
tq_str('sa1ls231')
sals
Process finished with exit code 0
7.写一个函数,求多个数的平均值
def my_aver(*num):
print(sum(num)/len(num))
my_aver(2,4,6,8,8)
5.6
Process finished with exit code 0
8.写一个函数,默认求10的阶层,也可以求其他数的阶层
def jc(a,b=10):
s = 1
for i in range(1,a+1):
s *= i
print(s)
m = 1
for j in range(1,11):
m *= j
print(m)
jc(6)
720
3628800
Process finished with exit code 0
9.写一个函数,可以对多个数进行不同的运算
例如:
operation('+', 1, 2, 3) ---> 求 1+2+3 的结果
operation('-', 10, 9) ---> 求 10-9 的结果
operation(' * ', 2, 4, 6, 8, 10) ---> 求 2 * 6 * 8 * 10 的结果
def operation(char,*num):
if char == '+':
print(sum(num))
elif char == '-':
if len(num):
sum1 = num[0]
for i in range(len(num)):
# 如果下标不是0,就减
if i:
sum1 -= num[i]
else:
pass
print(sum1)
elif char == '*':
s = 1
for i in num:
s *= i
print(s)
operation('+',5,4,6,8)
operation('-',5,4,3)
operation('*',5,4,6)
23
-2
120
Process finished with exit code 0
网友评论