myList = [1, 2, 3, 4]
myList.insert(2, 10)
help(myList.insert)
#Help on built-in function insert:
#
#insert(index, object, /) method of builtins.list instance
# Insert object before index.
The def (define 定義) keyword:
def functionName(input1, input2, ...):
function code here
input: 可給任一個, 甚至不給:
# sample 1
def sayHi():
print("Hello, how are you?")
# function execution, invokation 程式執行
sayHi()
print(sayHi)
#<function sayHi at 0x7f8cc80e80d0> function sayHi儲存位置
# sample 2
def addition(x, y): # x, y are parameter 參數
print(x + y)
addition(23, 19) # 42, 23, 19 are the arguments
a = 30
b = 25
addition(a, b) # 55, arguments can be variables as well
parameters & arguments
從sample 2來看:
x, y are the parameters (參數) : 定義function時所使用的 variable
23, 19 are the arguments : 在執行這個function時所給定的確切的值
addition(a, b) : argument也可以是variable
global variables, local variables
a = 5 # global variable
def f1():
x = 2 # f1 function's local variable
y = 3 # f1 function's local variable
print(x, y, a)
def f2():
x = 10 # f2 function's local variable
y = 17 # f2 function's local variable
print(x, y, a)
f1() # 2 3 5
f2() # 10 17 5
print(x, y) # NameError: name 'x' is not defined