习题 12: 提示别人

阅读原文

当你键入 raw_input() 的时候,你需要键入 () 也就是“括号(parenthesis)”。 这和你格式化输出两个以上变量时的情况有点类似,比如说 "%s %s" % (x, y) 里边就 有括号。对于 raw_input 而言,你还可以让它显示出一个提示,从而告诉别人应该输入 什么东西。你可以在 () 之间放入一个你想要作为提示的字符串,如下所示:

y = raw_input("Name? ")

这句话会用 “Name?” 提示用户,然后将用户输入的结果赋值给变量 y。这就是我们 提问用户并且得到答案的方式。

也就是说,我们的上一个练习可以使用 raw_input 重写一次。所有的提示都可以通过 raw_input 实现。

age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)

What You Should See

$ python ex12.py
How old are you?  38
How tall are you?  6'2"
How much do you weigh?  180lbs
So, you're '38' old, '6\'2"' tall and '180lbs' heavy.

Study Drills

  1. 在命令行界面下运行你的程序,然后在命令行输入 pydoc raw_input 看它说了些什么。
  2. 输入 q 退出 pydoc。
  3. 上网找一下 pydoc 命令是用来做什么的。
  4. 使用 pydoc 再看一下 open, file, os, 和 sys 的含义。看不懂没 关系,只要通读一下,记下你觉得有意思的点就行了。

Common Student Questions

How come I get SyntaxError: invalid syntax whenever I run pydoc?
You aren't running pydoc from the command line; you're probably running it from inside python. Exit out of python first.
Why does my pydoc not pause like yours does?
Sometimes if the help document is short enough to fit on one screen then pydoc will just print it.
When I run pydoc I get more is not recognized as an internal.
Some versions of Windows do not have that command, which means pydoc is broken for you. You can skip this Study Drill and just search online for Python documentation when you need it.
Why would I use %r over %s?
Remember %r is for debugging and is "raw representation" while %s is for display. I will not answer this question again so you must memorize this fact. This is the #1 thing people ask repeatedly, and asking the same question over and over means you aren't taking the time to memorize what you should. Stop now, and finally memorize this fact.
Why can't I do print "How old are you?" , raw_input()?
You'd think that'd work, but Python doesn't recognize that as valid. The only answer I can really give is, you just can't.

Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong

results matching ""

    No results matching ""