To define a function in Python, we need to use the keyword "def". The basic syntax of defining a function is:
def functionName(input1, input 2, …):
function code here
Inputs are optional; if we don’t need inputs, then we just keep the empty parenthesis.
Inputs are the local variables in the function; they are either copy by value or reference
You can also use doctring (or documentation string) to give explanations or comments for a function.
#Parameter and argument
a = 30
b = 40
# x, y are parameters
def addition(x, y):
print(x + y)
addition(15, 20) # 15, 20 are arguments
addition(a, b) # argument 也可以是variable
-------------------------------------------
35
70
# global variable / local variable
a = 20 # global variable 不同的function 皆可代入
def f1():
x = 2 # local variable 只在function f1 內有效
y = 3 # local variable 只在function f1 內有效
print(x, y, a) # a 會指向外層的global variable
f1()
def f2():
m = 4 # local variable 只在function f2 內有效
n = 5 # local variable 只在function f2 內有效
print(m, n, a) # a is global variable
print(m, n, x) # **x is the f1 function local variable NOT callabl**e
f2()
--------------------------------
2 3 20
4 5 20
Traceback (most recent call last):
File "d:\\2022_python_\\u5168\\u653b\\u7565\\tempCodeRunnerFile.py", line 20, in <module>
f2()
File "d:\\2022_python_\\u5168\\u653b\\u7565\\tempCodeRunnerFile.py", line 17, in f2
print(m, n, x)
NameError: name 'x' is not defined
# change by value and by reference
a = 10
def change(num): # input 是local variable in function
num = 25 # num = a (copy by value a是int)
change(a) # 執行def function
print(a) # 預期 a 從 10 變成 25 但結果還是 10
------------------------
10
# --------------------
a = [1, 2, 3, 4]
def change(lst):
lst[0] = 100 # copy by reference 會指向外層的 a
change(a)
print(a)
----------------------
[100, 2, 3, 4]
# can we change any copy by value global variables ?
a = 10
def change(num): # input 是local variable in function
global a # global keyword 是專用字 直接宣告 a 會指向外層的a
num = 25 # num = a (copy by value)
change(a) # 執行def function
print(a) # 預期 a 從 10 變成 25 yes --> change to 25
---------
25