練習 29 if 語句
這個練習中的 Python 腳本將帶你了解 if 語句。輸入代碼,準確運行,然后我們來看看你都學到了什么。
ex29.py
1 people = 20
2 cats = 30
3 dogs = 15
4
5
6 if people < cats:
7 print("Too many cats! The world is doomed!")
8
9 if people > cats:
10 print("Not many cats! The world is saved!")
11
12 if people < dogs:
13 print("The world is drooled on!")
14
15 if people > dogs:
16 print("The world is dry!")
17
18
19 dogs += 5
20
21 if people >= dogs:
22 print("People are greater than or equal to dogs.")
23
24 if people <= dogs:
25 print("People are less than or equal to dogs.")
26
27
28 if people == dogs:
29 print("People are dogs.")
你會看到
練習 29 會話
$ python3.6 ex29.py
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.
附加練習
在附加練習中,試著猜猜 if 語句是什么以及它是干什么的。在繼續(xù)進行下個練習之前,試著用自己的話回答以下這些問題,
- 你認為 if 對它下面的代碼起什么作用?
- 為什么 if 下面的代碼要縮進 4 個空格?
- 如果沒有縮進會發(fā)生什么?
- 你能從練習 27 里面把一些布爾表達式放進 if 語句嗎?試試看。
- 如果你改變 people,cats 和 dogs 的初始值會發(fā)生什么?
常見問題
+= 是什么意思? x += 1 就相當于 x = x + 1 ,但是輸入的內容更少。你可以把它叫做“累加”(increment by)運算符。之后你還會學到 -= 這樣類似的表達。