我的视频学习笔记
定义函数 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