視頻位置:151:00
本節學習函數。
當我們構建大型的複雜程序時,我們應該把代碼分解成更小的可重複使用的塊,即函數。如input(),print()都是內置的函數。
#先定義才能調用
def greet_user(): #小寫開頭,多個單詞用下劃線連接,
print("hello world")
print("welcome aboard")
# 在定義函數後要空兩行
print("start")
greet_user() #只有被調用時才執行函數裏的語句。
print("Finish")
輸出爲:
start
hello world
welcome aboard
Finish
函數就相當於封裝好的功能庫。
接下來,傳遞信息給函數。
def greet_user(name): #小寫開頭,多個單詞用下劃線連接,
print(f"hello {name}")
print("welcome aboard")
# 在定義函數後要空兩行
print("start")
greet_user("jonh") #如果這裏沒有輸入,會報錯
print("Finish")
輸出爲:
start
hello jonh
welcome aboard
Finish
兩個參數。
def greet_user(first_name,last_name): #小寫開頭,多個單詞用下劃線連接,
print(f"hello {first_name} {last_name}")
print("welcome aboard")
# 在定義函數後要空兩行
print("start")
greet_user("jonh","smith") #如果交換位置,就成了hello smith jonh
print("Finish")
評論中有人提到了形參和實參,我自己覺得吧,就是上面first_name和john的區別,一個是佔位的,一個是具體的。
輸出結果:
start
hello jonh smith
welcome aboard
Finish
我們也可以指定哪個對應哪個,比如
def greet_user(first_name,last_name): #小寫開頭,多個單詞用下劃線連接,
print(f"hello {first_name} {last_name}")
print("welcome aboard")
# 在定義函數後要空兩行
print("start")
greet_user(last_name="jonh",first_name="smith") #不能只寫first_name ,不寫last_name 要寫兩個都得寫
print("Finish")
上面的好處是提高代碼可讀性。
接下來,讓函數有返回值
def square(number):
return number * number
result = square(3)
print(result)
輸出爲:
9
然而,如果這樣寫:
def square(number):
print(number * number)
result = square(3)
print(result)
輸出爲:
9
None
上面,計算了3*3,返回值是空。如果沒有return就會這樣。
小練習,將之前學的(如下)的這個程序改編成函數。
注意:input 和print都不要改到函數裏,因爲輸入、輸出的方式有很多,不要封裝起來。
message = input(">")
words = message.split(' ') #將字符串分割成多個單詞,分隔關鍵詞爲‘’裏面的內
emojis = {
":)":"lalalala",
":(":"55555555"
}
output = ""
for word in words:
output += emojis.get(word,word) +" "
print(output)
我的改編如下:
def translate():
words = message.split(' ') #將字符串分割成多個單詞,分隔關鍵詞爲‘’裏面的內
emojis = {
":)":"lalalala",
":(":"55555555"
}
output = ""
for word in words:
output += emojis.get(word,word) +" "
return output
message = input(">")
print(translate()) #此處不能print(output)
輸出如下:
>I am sad :)
I am sad lalalala
我感覺上函數沒有輸入項怪怪,改了一下也行:
def translate(message):
words = message.split(' ') #將字符串分割成多個單詞,分隔關鍵詞爲‘’裏面的內
emojis = {
":)":"lalalala",
":(":"55555555"
}
output = ""
for word in words:
output += emojis.get(word,word) +" "
return output
#message2 = input(">")
#print(translate(message2)) #注意這裏我添了一個2,不加也行
message = input(">")
print(translate(message))
視頻位置173:40