原文鏈接:http://learnpythonthehardway.org/book/ex14.html
現在讓我們來做一個同時使用 argv 和 raw_input 兩個方法來詢問用戶一些特別的事情的練習。在做下一個練習前你得學會如何讀和寫像下面示例的腳本。在這次練習中,我們將使用 raw_input 的方式稍微有點不同,不同之處在於我們用它只簡單的輸出一個 “>” 提示符。這有點像Zork 或者 Advacne遊戲。
from sys import argv
script ,user_name = argv
prompt = '>'
print "Hi %s, I'm the %s script." % (user_name ,script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright ,so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer.Nice.
"""% (likes ,lives ,computer)
注意到我們創建了一個 prompt 變量來作爲我們想要設置的提示符,我們把它放在 raw_input 中來避免反反覆覆的打印它。現在如果我們想要使其他提示符的話,只要返回腳本中修復 prompt 這個變量的值就行了。
非常方便!
輸出結果如下:
c:\>python ex14.py zed
Hi zed, I'm the ex14.py script.
I'd like to ask you a few questions.
Do you like me zed?
>Yes
Where do you live zed?
>San Francisco
What kind of computer do you have?
>Tandy 1000
Alright ,so you said 'Yes' about liking me.
You live in 'San Francisco'. Not sure where that is.
And you have a 'Tandy 1000' computer.Nice.
研究訓練:
1、找出 Zork 和 Adventure 是什麼樣的遊戲。試着找到一個副本並玩一下這個遊戲。
2、完全的改變變量prompt 的值。
3、在你的腳本中添加一個新的參數並使用它。
4、確保你能明白最後一行打印輸出中使用了"""風格的多行字符串並用%格式化輸出變量的使用形式。