1.编写一个函数,求1 + 2 + 3 + ... + N
def my_sum(*numbers):
sum1 = 0
numbers = int(input('请输入一个整数:'))
for item in range(1, numbers+1):
sum1 += item
print(sum1)
my_sum()
2.编写一个函数,求多个数中的最大值
def max1(*numbers):
count = 0
for item in numbers:
if item > count:
count = item
print('最大值为:%d' % count)
max1(10,20,120,50,90,100)
3.编写一个函数,实现摇色子的功能,打印n个色子的点数和
import random
def sum1():
n = int(input('请输入要多少次骰子:'))
sum = 0
for _ in range(n):
num = random.randint(1, 6)
print('点数为:', num)
sum += num
print('总点数为:', sum)
sum1()
4.编写一个函数, 交换指定字典的key和value。
例如: {'a': 1,'b': 2,'c': 3} ---> {1: 'a', 2: 'b', 3: 'c'}
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {}
def change1():
dict2 = {value: key for key, value in dict1.items()}
print(dict2)
change1()
5.编写一个函数,三个数中的最大值
def max1(*numbers):
count = 0
for item in numbers:
if item > count:
count = item
print('最大值为:%d' % count)
max1(120,90,100)
6.编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
例如: ' 12a&bc12d--' - -->打印' abcd '
def print1():
str = input('请输入:')
for x in str:
if x.isalpha():
print('%s'% x, end='')
print1()
print()
7.写一个函数,求多个数的平均值
def ave1(*numbers):
sum1 = 0
count = 0
ave2 = 0
for x in numbers:
sum1 += x
count += 1
ave2 = sum1/count
print('平均值:',ave2)
ave1(10,20,30)
8.写一个函数,默认求10的阶层,也可以求其他数的阶层
def my_sum(*numbers):
sum1 = 1
numbers = int(input('请输入一个整数:'))
for item in range(1, numbers+1):
sum1 *= item
print(sum1)
my_sum()
9.写一个函数,可以对多个数进行不同的运算
例如: operation('+', 1,2,3) --->求1 + 2 + 3
的结果
operation('-',10,9) --->求10 - 9
的结果
operation('*',2,4,8,10) --->求2 * 4 * 8 * 10
的结构
def operation(a,*numbers):
if a == '+':
sum1 = 0
for item in numbers:
sum1 += item
print(sum1)
if a == '-':
sub1 = numbers(2)
for item in numbers:
sub1 -= item
print(sub1)
if a == '*':
mul1 = 1
for item in numbers:
mul1 *=item
print(mul1)
operation('-',1,2,3)
网友评论