笨辦法學python習題31 做出決定

2021-08-11 11:29:47 字數 2596 閱讀 9027

這次的習題學習的是if/elif/else的用法,另外在附加習題中新增一些判斷條件時,對raw_input的用法更深刻。

首先還是上**(包含附加題中新增的一段):

print"you enter a dark room with two doors. do you go through door #1 or door #2 or door #3?"

door = raw_input(">")

if door == "1":

print"there's a giant bear here eating a cheese cake.what do you do?"

print"1.take the cake."

print"2.scream at the bear."

bear = raw_input(">")

if bear =="1":

print"the bear eats your face off. good job!"

elif bear == "2":

print"the bear eats your legs off. good job"

else:

print"well,doing %s is probably better.bear runs away." %bear

elif door =="2":

print"you stare into the endless abyss at cthulhu's retina."

print"1.blueberries."

print"2.yellow jacket clothespins."

print"3.understanding revolvers yelling meldies."

insanity = raw_input(">")

if insanity =="1" or insanity =="2":

print"your body survives powered by a mind of jello. good job!"

else:

print"the insanity rots your eyes into a pool of muck. good job!"

elif door == "3":

print"""there is a angle in front of you,

he will help you out.

please pray"""

pray_count = raw_input(">")

if pray_count == "500":

print"the angle help you out,congratulation!"

else:

print"the angle can't decide."

else:

print"you stumble around and fall on a knife and die. good job"

1,首先說明一下if 和 elif else在使用上的區別:

①if語句的每乙個條件都會進行判斷,在程式執行過程中會對if語句的判斷條件進行遍歷判斷,耗時較多

②if 語句中可以有多個elif的判斷條件,但結尾只有乙個else語句。

③elif後面接判斷條件,else無判斷條件。

④舉個栗子,說明if與elif的區別:

a= true , b = true

if a:

print"a"

if b:

print"b"

這種寫發,輸出的是a和b。

a= true , b = true

if a:

print"a"

elif b:

print"b"

這種寫法,輸出的是a

a= false , b = true

if a:

print"a"

elif b:

print"b"

這種寫法,輸出的是b.

elif的意思是「否則的話,如果……」

2,最後說一下raw_input的部分,在附加題中自己新增的一段**如下:

elif door == "3":

print"""there is a angle in front of you,

he will help you out.

please pray"""

pray_count = raw_input(">")

if pray_count == "500":

print"the angle help you out,congratulation!"

else:

print"the angle can't decide."

黃色mark部分,前面寫的時候寫成if pray_count == 500:

這個時候不論輸入的是不是500,輸出永遠是:the angle can't decide.後面想到「raw_input() 將所有輸入作為字串看待,返回字串型別」,因此在將500修改為「500」後異常得以解除。

再小的技能都值得認真對待!!!

《笨辦法學python》習題38 40

mystuff 然後作者又給出了乙個錯誤的情況 class thing object def test hi print hia thing a.test hello 錯誤原因是test 只可以接受乙個引數,卻給了兩個。也就是 a.test hello 實際上是test a,hello 從這裡開始到...

《笨辦法學Python》 習題3

加分習題 系統 mac os 10.14 python 2.7.10 版本 笨辦法學python 第四版 print i will now count my chickens print hens 25 30 6.0 print roosters 100 25 3 4 print now i wil...

《笨辦法學Python》 習題6

加分習題 系統 mac os 10.14 python 2.7.10 版本 笨辦法學python 第四版 x there are d types of people.10 binary binary do not don t y those who know s and those who s.bi...