莫烦 Python 基础 函数

本文深入探讨了Python中函数的定义与使用,包括带有参数的函数定义、默认参数的应用,以及全局与局部变量的区别。通过实例展示了如何定义函数、使用默认参数,并解释了全局变量与局部变量的作用范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的视频学习笔记
定义函数 def 带参数

def function(a, b):
    print('this is a function')
    c = a * b
    print('the c is :', c)

function(1, 6)
function(a=2, b=5)

输出:

this is a function
the c is : 6
this is a function
the c is : 8

函数默认参数
未被默认赋值的参数要写在默认值的前面,赋值的时候也是一样的
对默认参数重新赋值,要在赋值语句中添加该参数名

def sale_car(price, brand, color='red', is_second_hand=True):
    print(
        'price:', price,
        'color:', color,
        'brand:', brand,
        'is_second_hand:', is_second_hand
    )

sale_car(1234, 'BMW', color='blue')

输出:

price: 1234 color: blue brand: BMW is_second_hand: True

全局&局部 global&local

APPLE = 100  # 通常全局变量 所有字母均用大写 全局变量在任何位置都可以取到
a = None
def fun():
    global a  # 如果一定要在函数里定义全局变量a,需要在前面加上global关键字
    a = APPLE  # 局部变量只能在函数里调用
    return a + 100

print('last a = ', a)
print(fun())
print('new a = ', a)

输出:

last a =  None
200
new a =  100
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值