当前位置:首页 > Python教程 > python技巧

笨办法学Python(十四)

习题 14:提示和传递

    让我们使用 argv 和 raw_input 一起来向用户提一些特别的问题。下一节习题你会学习如何读写文件,这节练习是下节的基础。在这道习题里我们将用略微不同的方法使用 raw_input,让它打出一个简单的 > 作为提示符。这和一些游戏中的方式类似,例如 Zork 或者 Adventure 这两款游戏。

    

技术分享 技术分享
                 1
                from sys import argv 
 2 3 script, user_name = argv 
 4 prompt = >  5 6print"Hi %s, I‘m the %s script." % (user_name, script) 
 7print"I‘d like to ask you a few questions." 8print"Do you like me %s?" % user_name 
 9 likes = raw_input(prompt) 
1011print"Where do you live %s?" % user_name 
12 lives = raw_input(prompt) 
1314print"What kind of computer do you have?"15 computer = raw_input(prompt) 
1617print"""18Alright, so you said %r about liking me. 
19You live in %r. Not sure where that is. 
20And you have a %r computer. Nice.
21""" % (likes, lives, computer)
View Code

    我们将用户提示符设置为变量 prompt,这样我们就不需要在每次用到 raw_input 时重复输入提示用户的字符了。而且如果你要将提示符修改成别的字串,你只要改一个位置就可以了。

    非常顺手吧。

 

 

    你应该看到的结果

    当你运行这个脚本时,记住你需要把你的名字赋给这个脚本,让 argv 参数接收到你的名称。

     技术分享

 

加分习题

  1. 查一下 Zork 和 Adventure 是两个怎样的游戏。 看看能不能下载到一版,然后玩玩看。

  2. 将 prompt 变量改成完全不同的内容再运行一遍。

  3. 给你的脚本再添加一个参数,让你的程序用到这个参数。

  4. 确认你弄懂了三个引号 """ 可以定义多行字符串,而 % 是字符串的格式化工具。

 

习题练习

1.

 

原文:http://www.cnblogs.com/yllinux/p/7257826.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐