Learn Python The Hard Way学习(14) - 提示和传递


让我们做一个把argv和raw_input结合使用的例子,为下个例子学习读写文件打下基础。在这个例子中,raw_input只给了一个简单的提示,有点像游戏Zork或者Adventure。

[python] 
1. from sys import argv 
2.  
3.  
4. script, user_name = argv 
5. prompt = '> ' 
6.  
7.  
8. print "Hi %s, I'm the %s script." % (user_name, script) 
9. print "I'd like to ask you a few questions." 
10. print "Do you like me %s?" % user_name 
11. likes = raw_input(prompt) 
12.  
13.  
14. print "Where do you live %s?" % user_name 
15. lives = raw_input(prompt) 
16.  
17.  
18. print "What kind of computer do you have?" 
19. computer = raw_input(prompt) 
20.  
21.  
22. print """
23. Alright, so you said %r about liking me.
24. You live in %r, Not sure where that is.
25. And you have a %r computer, Nice.
26. """ % (likes, lives, computer) 

我们设置了一个prompt变量,在raw_input中做参数,这样就不用每次都写这个参数了,而且修改的时候修改一个地方就可以了,很方便吧。

运行结果
root@he-desktop:~/mystuff# python ex14.py eric
Hi eric, I'm the ex14.py script.
I'd like to ask you a few questions.
Do you like me eric?
> yes
Where do you live eric?
> China
What kind of computer do you have?
> Candy

Alright, so you said 'yes' about liking me.
You live in 'China', Not sure where that is.
And you have a 'Candy' computer, Nice.

root@he-desktop:~/mystuff#

加分练习
1. 找Zork和Adventure游戏来玩玩。

2. 改变变量prompt,然后重新执行一次。

3. 添加一个其他的参数到程序中。

4. 确认弄懂了"""表示多行输出,%是表示格式化媒介。

 作者:lixiang0522

相关内容

    暂无相关文章

评论关闭