函式(function)就像一個神奇機器一樣你丟東西進去(Input)就會有特定的東西跑出來(Output)。
1.擴展性高
2.可以比較容易的Debug
3.使程式比較易讀
[In]def test1(cat,car):
print(f"{cat} drives the {car}")
test1("Andy","car")
[Out]
Andy drives the car
def test1(cat,car):
print(f"{cat} drive the {car}")
test1(cat="andy",car="car")
[Out]
andy drive the car
[In]
def test1(cat,car,cars,car_number="500"):
print(f"{cat} drives the {car} and park have {car_number} {cars}.")
test1(cars="cars",cat="Andy",car="car")
[Out]
Andy drives the car and park have 500 cars.
[In]
def test1(cat,car,cars,car_number="500"):
print(f"{cat} drives the {car} and park have {car_number} {cars}.")
test1(cars="cars",cat="Andy",car="car",car_number="69")
[Out]
Andy drives the car and park have 69 cars.
變數的有效範圍會影響到是否可以讀取。
[In]
def number():
z=1
print(z)
[Out]
NameError Traceback (most recent call last)
<ipython-input-1-bdf3712d3bb0> in <module>
1 def number():
2 z=1
----> 3 print(z)
NameError: name 'z' is not defined
def namber():
z=30 #Local Variable
print(z)
[Out]
69
[In]
z=69 #Global Variable
def namber():
global z
z=30 #Local Variable
namber()
print(z)
[Out]
30
1.如果要輸入大量參數,可以使用*來打包
[In]
def park_lot(*result):
print(result)
park_lot("BMW","Benz","Toyota","porsche")
[Out]
('BMW', 'Benz', 'Toyota', 'porsche')
2.如果要將資料打包成字典(Dictionary)形式則用**
[In]
def park_lot(**result):
##打包成字典(Dictionary)資料型態,
##在呼叫函式時,一定要使用關鍵字參數(Keyword Argument)
print(result)
park_lot(brand1="BMW",brand2="Benz",brand3="Toyota",brand4="porsche")
[Out]
{'brand1': 'BMW', 'brand2': 'Benz', 'brand3': 'Toyota', 'brand4': 'porsche'}
[In]
def number(*val):
total=5
for val in val:
if val %10:
total != val #!=檢查兩個操作數的值是否相等,如果值不相等,則條件變為真。
return total
numbers=number(1,2,3,4)
print(numbers)
#in 用來判斷複合資料型態如串列 (list) 、字串 (string)
#等是否包含指定元素,字典 (dictionary)
#方面則是判斷是否包括指定的 key 。
[Out]
5
[In]
def number(*val):
total=5
for val in val:
if val %5:
total != val #!=檢查兩個操作數的值是否相等,如果值不相等,則條件變為真。
#in 用來判斷複合資料型態如串列 (list) 、字串 (string)
#等是否包含指定元素,字典 (dictionary)
#方面則是判斷是否包括指定的 key 。
print(total)
number(1,2,3,4)
[Out]
5
打包成字典(Dictionary)資料型態,在呼叫函式時,一定要使用關鍵字參數(Keyword Argument)。
今天份的def筆記講解結束。