函數是帶名字的代碼塊,用於完成具體的工作。
無參數、無返回值函數
# 無參數、無返回值函數
def say_hello():
print('hello')
say_hello()
有參數,無返回值函數
# 有參數,無返回值函數
def say_hello(name):
print('hello ' + name)
say_hello('Thomas')
位置實參
# 位置實參
def say_hello(name , age):
print('hello '+name+' , age : '+str(age))
say_hello('Thomas', 5)
關鍵字實參
使用關鍵字實參時,務必準確地指定函數定義中的形參名。
# 關鍵字實參
def say_hello(name,age):
print('hello '+name+' , age : '+str(age))
say_hello(name='Thomas', age=5)
有返回值函數
# 返回值
def get_message(name,age):
return 'hello ' + name + ' , age : ' + str(age)
message = get_message('Thomas', 5)
print(message)