编写函数,求1+2+3+…N的和
def m_sum(n):
sum1=0
for items in range(n+1):
sum1=sum1+items
return sum1
print(m_sum(100))
2.编写一个函数,求多个数中的最大值
def m_max(*nums):
max1=nums[0]
for items in nums:
if items >max1:
max1 =items
return max1
print(m_max(1,2,3,4,5))
3.编写一个函数,实现摇骰子的功能,打印N个骰子的点数和
import random
def dice(n):
sum1=0
num_list=[]
while n> 0:
num_list.append(random.randint(1,6))
n=n-1
return sum(num_list)
n = int(input("要摇几次骰子"))
print('总和是:%d'% dice(n))
4.编写一个函数,交换指定字典的key和value
例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}
def change_dict(dic):
for key in dic:
new_key=dic[key]
new_value=key
dic.pop(key)
dic[new_key] =new_value
return dic
dict1={'a':1,'b':2,'c':3}
print(change_dict(dict1))
5.编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
例如: 传入'12a&bc12d-+' --> 'abcd'
def extract_letters(str1):
new_str=''
for item in str1:
if 'a'<=item<='z' or 'A'<=item<='Z':
new_str+=item
return new_str
str1=input('输入字符串')
print('提取字符串:')
print('提取字母: %s' %extract_letters(str1))
6.写一个函数,求多个数的平均值
def ave(nums):
aver=sum(nums)/len(nums)
return aver
num_list=[]
num_str=input('输入一串数字,空格隔开:')
new_str=[]
new_str=num_str.split(' ')
for item in new_str:
num_list.append(int(item))
print('平均值是: %.2f' % ave(num_list))