函数进阶-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)

若有侵权,请联系作者

相关推荐
浪浪山齐天大圣30 分钟前
python数据可视化之Matplotlib(8)-Matplotlib样式系统深度解析:从入门到企业级应用
python·matplotlib·数据可视化
F_D_Z41 分钟前
【PyTorch】单对象分割
人工智能·pytorch·python·深度学习·机器学习
编程自留地43 分钟前
18.4 查看订单
python·django·商城
wanzhong23331 小时前
学习triton-第1课 向量加法
开发语言·python·高性能计算
浊酒南街1 小时前
Pytorch基础入门4
人工智能·pytorch·python
dragon_perfect1 小时前
全流程基于Yolov8实现在Label-Studio实现半自动标注,已经把整个流程理清楚,把所有的坑解决。
开发语言·python·yolo·labelstudio
kalvin_y_liu1 小时前
四款主流深度相机在Python/C#开发中的典型案例及技术实现方案
开发语言·python·数码相机
AI Echoes1 小时前
LLMOps平台:开源项目LMForge = GPTs + Coze
人工智能·python·langchain·开源·agent
王伯安呢1 小时前
Python实战:爬取百度热搜榜,制作动态可视化报告
python·百度·中文分词·jieba·新手教程·技术教程
SUNxRUN2 小时前
【Python - 类库 - PyMySQL】(02)使用“PyMySQL“插入变量
python·pymysql