函式式編程與程序式編程打的區分:程序是沒有回傳值的函式,程序在python3中也有回傳值,為None
函式的作用:代碼復用、保持代碼的一致性、使代碼更容易擴展
程序的定義與呼叫:
1 def func2():
2 """testing2""" # 程序的描述
3 print("in the func2")
4 y=func2()
5 print(y)
6 # >>> in the func2
7 # >>> None
函式的定義與呼叫:
1 def func1(): 2 """testing1""" # 函式的描述 3 print("in the func1") 4 return 0 #結束函式、回傳可被變數接收的值 5 print("你猜會不會列印我") 6 x=func1() 7 print(x) 8 # >>> in the func1 9 # >>> 0
函式回傳值可以為多個值,且值的資料型別可以有多種
1 def func1(): 2 """testing1""" # 函式的描述 3 print("in the func1") 4 return 1, ["a", "b"], {"name": "abc"}, "hello" 5 x=func1() 6 print(x) 7 # >>> in the func1 8 # >>> (1, ['a', 'b'], {'name': 'abc'}, 'hello') #元組
函式回傳值為另一個函式時,回傳另一個函式的記憶體地址
1 def func(): 2 print("I`m func") 3 return 0 4 5 def func1(): 6 """testing1""" # 函式的描述 7 print("in the func1") 8 return func 9 x=func1() 10 print(x) 11 # >>> in the func1 12 # >>> <function func at 0x00000223A2ADC040>
模擬程式呼叫日志函式,列印日志到檔案(帶時間):
1 import time 2 def logger(): 3 time_format = '%Y-%m-%d %X' # 定義輸出的時間格式 4 # strftime() 函式接收以時間元組,并回傳以可讀字串表示的當地時間,以定義的時間格式輸出時間 5 time_current = time.strftime(time_format) 6 with open('a.txt', 'a+') as f: 7 f.write('%s end action\n' % time_current) 8 return 0 9 10 def test1(): 11 print('in the test1') 12 logger() 13 return 0 14 15 def test2(): 16 print('in the test2') 17 logger() 18 return 0 19 20 test1() 21 test2()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/143933.html
標籤:Python
上一篇:Python--函式傳參
下一篇:Python--編碼轉換
