函數(Function)和方法(Method)差別在於是否需要和對象(object)進行關聯
當看到不知道的函數或方法,可以利用以下兩種方式去查看: 1.使用Python中內建的 help( ) 函數查詢 2.使用官方的說明文檔進行查詢 https://docs.python.org/3/
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.
Python官方的說明文檔(3.7.13) 網址:https://docs.python.org/3.7/tutorial/datastructures.html
list.**insert**
(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x)
inserts at the front of the list, anda.insert(len(a), x)
is equivalent toa.append(x)
.
函數基本語法如下:
# define function
def functionName(input1, input2, …):
'''doctring'''
function code
return
# function execution / invokation
functionName(input1, input2, …)
# 沒有input的函數
def sayHi():
print("Hello, how are you?")
print(sayHi) # 查看函數sayHi所在的記憶體位置
sayHi() #執行/調用sayHi這個函數
--------------------------------------------
# 執行結果:
<function sayHi at 0x000001EC54C11438>
Hello, how are you?
# 有input的函數
def addition(x, y): #其中的x,y叫做parameter
print(x + y)
addition(15, 35)
--------------------------------------------
# 執行結果:
50