笨办法学Python(十四)
2024-08-30 18:04:13
习题 14:提示和传递
让我们使用 argv 和 raw_input 一起来向用户提一些特别的问题。下一节习题你会学习如何读写文件,这节练习是下节的基础。在这道习题里我们将用略微不同的方法使用 raw_input,让它打出一个简单的 > 作为提示符。这和一些游戏中的方式类似,例如 Zork 或者 Adventure 这两款游戏。
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 时重复输入提示用户的字符了。而且如果你要将提示符修改成别的字串,你只要改一个位置就可以了。
非常顺手吧。
你应该看到的结果
当你运行这个脚本时,记住你需要把你的名字赋给这个脚本,让 argv 参数接收到你的名称。
加分习题
1. 查一下 Zork 和 Adventure 是两个怎样的游戏。 看看能不能下载到一版,然后玩玩看。
2. 将 prompt 变量改成完全不同的内容再运行一遍。
3. 给你的脚本再添加一个参数,让你的程序用到这个参数。
4. 确认你弄懂了三个引号 """ 可以定义多行字符串,而 % 是字符串的格式化工具。
习题练习
2.
3.
from sys import argv script, user_name, who = 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
print "who are you %s?" % who
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 "who?"
name = 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, %r.
""" % (likes, lives, computer, who)
最新文章
- PHP global 关键字
- python中*args和**args的不同
- Emacs简易教程
- iOS - MVC 架构模式
- cuffdiff 和 edgeR 对差异表达基因的描述
- 第一课 opengl简介
- iOS之事件穿透
- FLV封装格式及分析器工具
- Oracle imp 不同字符集导入
- toast组件较为完美版本
- cf B. Flag Day
- Js 时间间隔计算(间隔天数)
- oracle 11g常用命令
- 深入探讨MFC消息循环和消息泵
- Java 基础类型转换byte数组, byte数组转换基础类型
- sql之cursor的简介和字符串拆分(split)与游标的使用
- CSS设置DIV边框为圆角,添加背景色溢出的问题
- tensorFlow(二)线性回归
- FTP 其他设置
- Win10 Edge浏览器怎么重装 Win10重装Edge浏览器
热门文章
- zmq导致master收不到minion的key
- django组件之ajax
- linux 学习2 (基于ubuntu)
- java中所有开源注解收集
- 搭建hadpoot平台(集群式分布)
- web前端开发道路
- Caused by: java.net.URISyntaxException: Relative path in absolute URI
- ubuntu 16.04下搜狗输入法不能输入中文解决
- CentOS 6.5 &; 7 的网络YUM源配置
- 服务间调用--feign跟ribbon