Exercise 31:做出決定

原文鏈接:http://learnpythonthehardway.org/book/ex31.html

       這本書的上半部分你打印了一些東西,而且調用了函數,不過一切都是直線式進行的。你的腳本從頂部開始運行一直運行到代碼底部結束。如果你創建了一個函數你可以在之後調用它運行,但這種形式始終不是一種真正的分支結構,不能讓你真正的做出不同的決定。現在你有了 if ,else 和 elif 你就可以開始讓你的腳本真正的決定哪些執行哪些不執行了。

       在上一次的腳本中你寫了一組簡單的提問測試。在這次的腳本中你需要詢問用戶問題,並且根據用戶的回答做出決定。把腳本寫下來,多多鼓搗一陣子,看看它的工作原理是什麼。

print "You enter a dark room with two doors. Do you go through door #1 or door #2"

door = raw_input("> ")

if door == "1":
	print "There's a giant bear 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 melodies."

	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!"

else:
	print "You stumble around and fall on a knife and die. Good job!"
      這裏最主要的就是你可以將一個if語句放在另一個if語句中運行。這是一個很強大的功能,可以用來創建嵌套(nested)的決定,其中的一個分支將引向另一個分支的子分支。

      確保你理解了if語句嵌套的概念。事實上,做一下研究訓練你就可以確認你自自己是否真的掌握了它。

輸出結果如下:

c:\>python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2
> 1
There's a giant bear eating a cheese cake. What do you do?
1.Take the cake.
2.Scream at the bear.
> 2
The bear eats your legs off. Good job!.

研究訓練:

爲遊戲添加新的部分,改變玩家做決定的位置。儘自己的能力擴展這個遊戲,不過別把遊戲弄得太怪異了。

學生遇見的常見問題:


可以用一組if/else來替代 elif 嗎?

答:在一些情況寫是可以的,它取決於你沒有給if/else是怎麼寫的。如果替換的話也就意味着Python需要去檢查每一個if/else組合,而不僅僅像if/elif/else這樣的只需要檢查一組。(ps:這裏有可能翻譯不準。)你可以嘗試一下找出它們的不同之處。


我怎麼表示一個數值變量在某個數值範圍內?

答:你有兩個選擇:使用 0 < x < 10 或者 1 <= x < 10,這是比較基礎的用法,或者你可以使用 x in range(1 ,10) 。


如果我想在 if/elif/else 代碼塊添加更多選項應該怎麼做?

答:簡單,只要爲每一種可能的選擇添加更多的 elif 代碼塊就可以了。

發佈了23 篇原創文章 · 獲贊 7 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章