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

来源:互联网 发布:怎样注销阿里云账号 编辑:程序博客网 时间:2024/06/11 06:49
让我们做一个把argv和raw_input结合使用的例子,为下个例子学习读写文件打下基础。在这个例子中,raw_input只给了一个简单的提示,有点像游戏Zork或者Adventure。

from sys import argvscript, user_name = argvprompt = '> '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_namelikes = raw_input(prompt)print "Where do you live %s?" % user_namelives = 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中做参数,这样就不用每次都写这个参数了,而且修改的时候修改一个地方就可以了,很方便吧。

运行结果
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. 确认弄懂了"""表示多行输出,%是表示格式化媒介。
原创粉丝点击