函数进阶-Python

师从黑马程序员

函数中多个返回值的接收

python 复制代码
def test_return():
    return 1,"hello",3

x,y,z=test_return()
print(x)
print(y)
print(z)

多种参数的使用

函数参数种类

位置参数

关键字参数

python 复制代码
def user_info(name,age,gender):
    print(f"姓名是{name},年龄是:{age},性别是:{gender}")

user_info(name='小王',age=11,gender='女')
user_info(age=0,gender='女',name='潇潇')#关键字参数可以不按照参数的定义顺序传参
user_info('甜甜',gender='女',age=9)#关键字参数和位置参数可以混用

缺省参数

默认参数一定要放在最后面

python 复制代码
def user_info(name,age,gender='男'):
    print(f"姓名是{name},年龄是:{age},性别是:{gender}")

user_info('小甜',13)
user_info('小甜',13,gender='女')

不定长参数

位置传递的不定长

形式参数会作为元组存在,接收不定长数量的参数传入

python 复制代码
def user_info(*args):
    print(f"args参数的类型是:{type(args)},内容是:{args}")

user_info(1,2,3,'小明','男孩')

关键字传递的不定长

python 复制代码
def user_info(**Kwargs):
    print(f"args参数的类型是:{type(Kwargs)},内容是:{Kwargs}")

user_info(name='小王',age=11,gender="男孩")

函数作为参数传递

函数可以接受数据作为参数传入:各种容器和另一个函数内

python 复制代码
def test_func(compute):
    result=compute(1,2)
    print(f"compute参数的类型是:{type(compute)}")
    print(f"计算结果:{result}")

def compute(x,y):
    return x+y

test_func(compute)

注:将函数传入的作用在于:传入计算逻辑,而非传入数据

lambda匿名函数

匿名函数与普通函数的比较

python 复制代码
def test_func(compute):
    result=compute(1,2)
    print(f"计算结果:{result}")


test_func(lambda x,y:x+y)
test_func(lambda x,y:x+y)

若有侵权,请联系作者

相关推荐
北斗落凡尘20 分钟前
LangGraph 入门实战(12)--使用MCP
后端·python·langchain
jdksjw41 分钟前
同步与异步、阻塞与非阻塞、多线程、协程超详细讲解(Python并发编程从入门到精通)
开发语言·python
Mike_Zhang1 小时前
使用python统计FreeSWITCH呼叫并发
python·freeswitch
SL-staff1 小时前
技术实践:HR如何用JVS-Logic可视化编排实现考勤数据同步(含节点配置与异常处理)
开发语言·python·低代码·钉钉·可视化编排·jvs-logic·hr技术
zzzzzz3103 小时前
AI 助手最危险的不是报错,而是“看起来成功”:我给工作流加了四道保险
人工智能·python
用户8356290780513 小时前
如何使用 Python 将 PowerPoint 转换为 PDF 文档
后端·python
菜冻鱼3 小时前
Python-pytorch-高级技巧
开发语言·人工智能·pytorch·python·深度学习·神经网络·聚类
lpfasd1233 小时前
python webview打包版卡死、开发版正常
开发语言·python
用户8356290780513 小时前
如何使用 Python 为 PowerPoint 幻灯片添加切换效果
后端·python
菜冻鱼4 小时前
Python-pytorch-模型保存与加载
开发语言·人工智能·pytorch·python·深度学习·机器学习