函數就是可重復使用的代碼片段。
函數的聲明與調用
如下例子
# Functions
# 函數聲明,通過def關鍵字來聲明
# 聲明函數
def first_func():
print('This is my first Python function.')
# 調用函數
first_func()
first_func()
first_func()
函數參數
具體怎么聲明一個帶有參數的函數,請參考下面的例子。
在定義函數時給定的參數名稱叫做形參(parameters)
,在調用函數式所提供給函數的值稱為實參(arguments)
。
# 聲明一個帶有參數的函數
def func_para(m,n):
if m > n:
print(m,'is the max number')
elif m < n:
print(n,'is the max number.')
else:
print(m,'is equal to ',n)
func_para(8,9)
func_para(5,2)
# 以參數的形式傳遞變量
x = int(input('請輸入一個數字:\n'))
y = int(input('請輸入另一個數字\n'))
func_para(x,y)