习题 11: 提问

阅读原文

我已经出过很多打印相关的练习,让你习惯写简单的东西,但简单的东西都有点无聊, 现在该跟上脚步了。我们现在要做的是把数据读到你的程序里边去。这可能对你有点难度, 你可能一下子不明白,不过你需要相信我,无论如何把习题做了再说。只要做几个练习 你就明白了。

一般软件做的事情主要就是下面几条:

  1. 接受人的输入。
  2. 改变输入。
  3. 打印出改变了的输入。

到目前为止你只做了打印,但还不会接受或者修改人的输入。你也许还不知道“输入(input)” 是什么意思。所以闲话少说,我们还是开始做点练习看你能不能明白。下一个习题里边我们 会给你更多的解释。

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

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

note:: 注意到我在每行 print 后面加了个逗号(comma) , 了吧?这样的话 print 就不会输出新行符而结束这一行跑到下一行去了。

What You Should See

$ python ex11.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. 上网查一下 Python 的 raw_input 实现的是什么功能。
  2. 你能找到它的别的用法吗?测试一下你上网搜索到的例子。
  3. 用类似的格式再写一段,把问题改成你自己的问题。
  4. 和转义序列有关的,想想为什么最后一行 '6\'2"' 里边有一个 \' 序列。单引号需要 被转义,从而防止它被识别为字符串的结尾。有没有注意到这一点?

Common Student Questions

How do I get a number from someone so I can do math?
That's a little advanced, but try x = int(raw_input()) which gets the number as a string from raw_input() then converts it to an integer using int().
I put my height into raw input like this raw_input("6'2") but it doesn't work.
You don't put your height in there, you type it directly into your Terminal. First thing is, go back and make the code exactly like mine. Next, run the script, and when it pauses, type your height in at your keyboard. That's all there is to it.
Why do you have a newline on line 8 instead of putting it on one line?
That's so that the line is less than 80 characters long, which is a style that Python programmers like. You could put it on one line if you like.
What's the difference between input() and raw_input()?
The input() function will try to convert things you enter as if they were Python code, but it has security problems so you should avoid it.
When my strings print out there's a u in front of them, as in u'35'.
That's how Python tells you that the string is Unicode. Use a %s format instead and you'll see it printed like normal.

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

results matching ""

    No results matching ""