day9 作业

编写函数,求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))
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 编写函数,求1+2+3+…N的和 sum2(100) 编写一个函数,求多个数中的最大值 编写一个函数,实现摇骰子的...
    嘿嘿_9c52阅读 283评论 0 0
  • """_ author _=陈泓羽""" 1.编写函数,求1+2+3+…N的和 2.编写一个函数,求多个数中的最大...
    依然羽阅读 550评论 0 0
  • 编写函数,求1+2+3+…N的和 编写一个函数,求多个数中的最大值 编写一个函数,实现摇骰子的功能,打印N个骰子的...
    归墟_a3c1阅读 332评论 0 0
  • """author = Zard"" 1.编写函数,求1 + 2 + 3 +…N的和 2.编写一个函数,求多个数中...
    Zard泉水阅读 167评论 0 0
  • // 适用于Charles任意版本的注册码// Charles 4.2目前是最新版,可用。Registered N...
    wlianfu阅读 378评论 0 0

友情链接更多精彩内容