Intro to Function and Methods

定義

遇到未知的method or function, 要怎麼辦?

  1. help() function
  2. google python documentation, 選版本, 查詢

3.9.16 Documentation

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.

寫自己的function

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

概念補充

  1. parameters & arguments

    從sample 2來看:

  2. 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