笨辦法學python ex30

2021-10-09 08:20:41 字數 2491 閱讀 2183

前一習題中你寫了一些 「if 語句(if-statements)」,並且試圖猜出它們是什麼,以 及實現的是什麼功能。在你繼續學習之前,我給你解釋一下上一節的加分習題的答案。上一節的加分習題你做過了吧,有沒有?

你認為 if 對於它下一行的**做了什麼? if 語句為**建立了乙個所謂的「分支」, 就跟 rpg 遊戲中的情節分支一樣。if 語句告訴你的指令碼: 「如果這個布林表示式為 真,就執行接下來的**,否則就跳過這一段。」

為什麼 if 語句的下一行需要 4 個空格的縮排? 行尾的冒號的作用是告訴 python 接下來你要建立乙個新的**區段。這根你建立函式時的冒號是乙個道理。

如果不縮排, 會發生什麼事情? 如果你沒有縮排,你應該會看到 python 報錯。 python 的規則裡,只要一行以「冒號(colon)」: 結尾,它接下來的內容就應該有縮排。

把習題 27 中的其它布林表示式放到 if 語句 中會不會也可以執行呢?試一下。可以。而且不管多複雜都可以,雖然寫複雜的東西通常是一種不好的程式設計風格。

如果把變數 people, cats, 和 dogs 的初始值改掉, 會發生什麼事情? 因為你比較的物件是數字,如果你把這些數字改掉的話,某些位置的 if 語句會被演繹 為 true,而它下面的**區段將被執行。你可以試著修改這些數字,然後在頭腦 裡假想一下那一段**會被執行。

把我的答案和你的答案比較一下,確認自己真正懂得**「區段」的含義。這點對 於你下一節的練習很重要,因為你將會寫很多的 if 語句。

把這一段寫下來,並讓它執行起來:

people = 30 

cars = 40

buses = 15

if cars > people:

print "we should take the cars."

elif cars < people:

print "we should not take the cars."

else:

print "we can't decide."

if buses > cars:

print "that's too many buses."

elif buses < cars:

print "maybe we could take the buses."

else:

print "we still can't decide."

if people > buses:

print "alright, let's just take the buses."

else:

print "fine, let's stay home then."

你應該看到的結果

$ python ex30.py 

we should take the cars.

maybe we could take the buses.

alright, let's just take the buses.

$

加分習題

猜想一下 elif 和 else 的功能。

將 cars, people, 和 buses 的數量改掉,然後追溯每乙個 if 語句。看看最後會 列印出什麼來。

試著寫一些複雜的布林表示式,例如 cars > people and buses < cars。

在每一行的上面寫註解,說明這一行的功用。

【python3**

people = 30

cars = 40

buses = 15

if cars > people:

print ("we should take the cars.")

elif cars < people:

print ("we should not take the cars.")

else:

print ("we can't decide.")

if buses > cars:

print ("that's too many buses.")

elif buses < cars:

print ("maybe we could take the buses.")

else:

print ("we still can't decide.")

if people > buses:

print ("alright, let's just take the buses.")

else:

print ("fine, let's stay home then.")

你應該看到的結果

we should take the cars. 

maybe we could take the buses.

alright, let's just take the buses.

笨辦法學python加分習題30

python版本 3 若有錯誤,敬請指出 模組名稱 測試.py 加分習題30 people 30 cars 40 buses 15 if cars people print we should take the cars.elif cars people print we should not ta...

笨辦法學Python

1.知識點 13節講的主要是module 模組 的概念,常用的語法是from xx import 依託於python強大的模組庫,使得呼叫十分輕鬆,功能十分強悍。argv叫做引數變數,可以理解為乙個包裹,在解包 unpack 的時候,將引數值賦給不同的變數名,其中第乙個變數是 隱藏 的,用來指代檔案...

笨辦法學Python(三十)

前一習題中你寫了一些 if 語句 if statements 並且試圖猜出它們是什麼,以及實現的是什麼功能。在你繼續學習之前,我給你解釋一下上一節的加分習題的答案。上一節的加分習題你做過了吧,有沒有?你認為 if 對於它下一行的 做了什麼?if 語句為 建立了乙個所謂的 分支 就跟 rpg 遊戲中的...