• 笨办法学Python(十四)


    习题 14:提示和传递

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

        

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

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

        非常顺手吧。

        你应该看到的结果

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

         

    加分习题

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

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

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

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

    习题练习

    2.

        

    3.

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

        

  • 相关阅读:
    Web安全测试检查点
    "Could not resolve host: mirrorlist.centos.org; Unknown error"解决方法
    VMware vSphere Client中启动虚拟机提示No boot filename received/Operating System not found解决方法
    Android:Mstar Android8.0平台音量控制流程
    Android:系统自定义鼠标样式切换
    Android:系统日历添加默认账户
    Android:状态栏禁用时蓝牙多文件传输弹窗及进度显示
    Android:导入所需的系统jar包到Android studio
    Android:修改连接到AP端显示的设备名
    Android:StateMachine 之 WifiStateMachine
  • 原文地址:https://www.cnblogs.com/yllinux/p/7257826.html
Copyright © 2020-2023  润新知