26、Python中函数额几种形式

Python初学者总结的Python用到的几种函数的形式:

# coding=utf-8

# python中函数的几种形式

# 第一种:无参数,无返回值
def fun1():
    x = 3
    print(x)

# 调用
x1 = fun1()

# 第二种:无参数,有返回值
def fun2():
    x = 3
    return x
print("函数fun2的值为:%s" % fun2())

# 第三种:有参数,无返回值
def fun3(x):
    y = x*x
    print(y)
fun3(3)

# 第四种:有参数,有返回值
def fun4(x):
    y = x * x
    return y
print("函数fun4的值为:%s" % fun4(4))

# 第五种:存在多个返回值,当存在多个返回值的时候,返回值的形式为元祖
def fun5(x):
    return x * x, x % 2

x2 = fun5(5)
print(x2)

# 第六种:函数中存在判断条件存在多个返回值
def fun6(x, y):
    if (x + y) % 2 == 0:
        return x + y
    else:
        return x - y
print(fun6(3, 4))
print(fun6(4, 4))

# 第七种:函数种形参给默认值
# 1、在函数调用中不传入形参
def fun7_1(x = 1, y = 2, z = 3):
    return x + y + z
print(fun7_1())

# 2、在函数中传入部分形参, 这里传入了2,3两个值对应的其实是给参数x,y进行重新赋值,z使用的是默认值
def fun7_2(x = 1, y = 2, z = 3):
    return x + y + z
print(fun7_1(2, 3))

# 3、在函数中传入所有参数,参数可以是无序的
def fun7_3(x = 1, y = 2, z = 3):
    return x + y + z
print(fun7_3(y=3,z=3,x=3))

# 第八种:函数中传入多个参数,返回值包含有元祖
def fun8(x, y, *z):
    return x, y, z
print(fun8(1,2,3,4,5,6,7,8)) # 打印结果为:(1, 2, (3, 4, 5, 6, 7, 8)),这里把默认多余的形参转换成了元祖对象

# 第九种:函数中传入多个参数,返回值为字典类型
def fun9(x, y, **z):
    return x, y, z
print(fun9(1, 2, a=1, b=2, c=3)) # 打印结果为:(1, 2, {'a': 1, 'b': 2, 'c': 3})后面参数因为是键值对,自动换成字典对象

# 第十种:多种参数进行组合:
def fun10(w=5, x=2, *y, **z):
    return w, x, y, z
print(fun10(1, 9, 3, 4, 5, 6, 7, a=1, b=2, c=3))
print(type(fun10()))
# 结果中 w进行重新赋值为1,x 重新赋值为9,y的值为3,4,5,6,7封装成元祖,a=1,b=2,c=3封装成字典,整体结果为元祖

# 第十一种:函数调用函数
def fun11_1(x, y):
    return x + y

def fun11_2(x, y):
    x = fun11_1(x, y)
    return x + y

print(fun11_2(2, 5))
# 执行过程,先调用函数fun11_2,传入参数2,5在函数fun11_2()中调用函数fun11_1()得到x的值为7,y的值为5,所以结果为12

sum = 1
# for i in range(5, 1, -1):
#     sum = sum * i
# print(sum)

for n in range(1, 6):
    sum = sum * n
print(sum)

# 第十二种:函数的递归
def fun12(num):
    if num > 1:
        return num * fun12(num-1)
    else:
        return num
print(fun12(6))

发布了30 篇原创文章 · 获赞 7 · 访问量 4704

猜你喜欢

转载自blog.csdn.net/qq969887453/article/details/91474724