python - 函数的返回值

1.函数调用时一般有返回值,没有定义返回值的时候,python中默认返回None

def hello():
    print('hello')

res = hello()
print(res)

输出:

hello
None

2.return

def hello():
    # return 返回的表达式或者变量
    return 'hello'

res = hello()
print(res)

输出:

hello

3.return的应用
要求:
1.随机生成20个学生的成绩
2.判断这个20个学生的等级

import random
    
def get_level(score):
    if 90 < score <= 100:
        return 'A'
    elif 80 < score <= 90:
        return 'B'
    else:
        return 'C'

def main():
    for i in range(20):
        score = random.randint(1,100)
        print('成绩为%s,等级为%s' %(score,get_level(score)))
        #注意这里函数调用的方法

在这里插入图片描述
4.多个返回值

def fun(a):
    # 接收一个列表,求这个列表的最大值,平均值,最小值
    max_num = max(a)
    min_num = min(a)
    avg_num = sum(a) / len(a)
    # python函数中,只能返回一个值
    # 如果非要返回多个值,会把返回的值封装为一个元组数据类型
    return max_num, min_num, avg_num
    
variables = fun([34, 1, 2, 3, 4, 5, 6, 7, 421])	#函数可以直接参数输入一个列表
print(variables, type(variables))

输出:

(421, 1, 53.666666666666664) <class 'tuple'>
#多个返回值结果封装成元组

猜你喜欢

转载自blog.csdn.net/weixin_43067754/article/details/84755908