1. 程式人生 > >python函式解釋

python函式解釋

實現某個功能的一些程式碼
提高程式碼的複用性
函式必須被呼叫才會執行
函式裡面定義的變數都叫區域性變數,只要一出了函式就不能用了
函式裡面如果呼叫時需要拿到結果但是最後沒寫return(不必須寫,如讀取檔案時就需要),則返回None
函式得先定義後使用,使用時注意先後順序

詳情:http://www.runoob.com/python3/python3-function.html

# 1. 定義一個可輸出hello world的函式
def hello(): # 定義函式用def
    print('hello world')
    
#呼叫函式1
hello() #呼叫函式,輸出hello world
# 2. 定義一個將content寫入file的函式 def write_file(file_name,content): #入參,不必須寫,根據需求 # 形參:形式引數 with open(file_name,'a+',encoding="utf-8") as fw: fw.write(content) # print(file_name,content) #以上程式碼為函式體 #呼叫函式2,將'123\n'寫入'a.txt'裡 write_file('a.txt','123\n') #實參:實際引數 # write_file('b.txt','456')
# write_file('c.txt','789') # 3. 定義一個可讀取並輸出file裡的content的函式 def read_file(file_name): with open(file_name, 'a+', encoding="utf-8") as fw: fw.seek(0) content = fw.read() return content #呼叫函式3 res = read_file('a.txt') print(res) #輸出a.txt裡面的內容