2018-08-29作业

1编写一个函数,求1+2+3+....+N

def func1():
    count = 0
    for x in range(1,N+1):
        count += x
    print(count)
N = int(input('输入一个整数N:'))
func1()
输出:
输入一个整数N:10
55

2.编写一个函数,求多个数中的最大值

def func2(*num):
    a = 0
    for item in num:
        if a < item:
            a=item
    print('最大值为:%d' % a)
func2(10,9,50,30,20,121)
输出:
最大值为:121

3.编写一个函数,实现摇色子的功能,打印n个色子的点数和

import random
def func3():
    count = 0
    n = int(input('几个色子点数相加:'))
    for x in range(n):
        point = random.randint(1,6)
        count += point
    print('%d个色子点数相加的和为:%d' % (n,count))
func3()
输出:
几个色子点数相加:3
3个色子点数相加的和为:9

5.编写一个函数,求三个数中的最大值

def func5(*nums):
    a = 0
    for item in nums:
        if a < item:
            a=item
    print('最大值为:%d' % a)

func5(10,90,45)
输出:
最大值为:90

6.编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
例如:'12a@bc$%1d--'---->打印'abcd'

def get_str(str1):
    new_str = ''
    for item in range(len(str1)):
        if str1[item].isalpha():
            new_str += str1[item]
    return new_str


print(get_str('12a@bc$%1d--'))
输出:
abcd

7.写一个函数,求多个数的平均值

def average(*number):
    count = 0
    for item in number:
        count += item
    avg = count/(len(number))
    print('平均值为:%.2f' % avg)
average(10,89,12)
输出:
平均值为:37.00

8写一个函数,默认值求10的阶乘,也可以求其他数的阶乘

def factorial(a = 10):
    count = 1
    for x in range(1,a+1):
        count *= x
    print('阶乘为:%d' % count)
factorial(5)
输出:
阶乘为:120

9.写一个函数可以对多个数进行不同的运算
例如:operation('+',1,2,3)---> 求1+2+3的结果
operation('-',10,9)---> 求10-9的结果
operation('',2,4,8,10)---> 求24810的结果

def operation(str2,*num):
    if str2 == '+':
        return sum(num)
    elif str2 == '-':
        number = num[0]
        for x in range(1,len(num)):
            number -= num[x]
        return number
    elif str2 == '*':
        count = 1
        for item in range(len(num)):
            count *= num[item]
        return count
    elif str2 == '/':
        number1 = num[0]
        for x in range(1,len(num)):
            number1 /= num[x]
        return number1

num1 = operation('+',1,2,3)
num2 = operation('-',10,9)
num3 = operation('*',2,4,8,10)
num4 = operation('/',8,4)
print(num1,num2,num3,num4,end = ' ')
输出:
6 1 640 2.0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 编写 个函数,求1+2+3+...+N 2.编写 个函数,求多个数中的最大值 编写 个函数,实现摇色子的功能,打印...
    叶叶阿姨阅读 97评论 0 0
  • 坚持星球,彼此加油!大家好,我是张桂华,今天我给大家分享的故事是,从0到1 的突破,我从不敢在公众面前说话,到今天...
    厦门整理师张桂华阅读 96评论 0 0
  • 编写一个函数,求1+2+3+...+N 2.编写一个函数,求多个数中的最大值 3.编写一个函数,实现摇色子的功能,...
    Deathfeeling阅读 160评论 0 1
  • 倘若置身广袤的无垠沙漠,我该如何穿越 倘若身体没有承受行李的负累,我该如何穿越 倘若没有被金城的年轻女郎诱惑,我该...
    裴文达阅读 221评论 7 1
  • 所有无法早早入睡的夜,就像所有无法早起的清晨。努力了,却无力改变。
    惠晶晶阅读 195评论 0 0