习题 4: 变量和命名
你已经学会了 print
和算术运算。下一步你要学的是“变量”。在编程中,变量只不过
是用来指代某个东西的名字。程序员通过使用变量名可以让他们的程序读起来更像英语。
而且因为程序员的记性都不怎么地,变量名可以让他们更容易记住程序的内容。如果他们
没有在写程序时使用好的变量名,在下一次读到原来写的代码时他们会大为头疼的。
如果你被这章习题难住了的话,记得我们之前教过的:找到不同点、注意细节。
- 在每一行的上面写一行注解,给自己解释一下这一行的作用。
- 倒着读你的
.py
文件。 - 朗读你的
.py
文件,将每个字符也朗读出来。
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
note
space_in_a_car
中的_
是下划线(underscore)
字符。你要自己学会 怎样打出这个字符来。这个符号在变量里通常被用作假想的空格,用来隔开单词。
What You Should See
$ python ex4.py
There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3 in each car.
Study Drills
当我刚开始写这个程序时我犯了个错误,python 告诉我这样的错误信息:
Traceback (most recent call last):
File "ex4.py", line 8, in <module>
average_passengers_per_car = car_pool_capacity / passenger
NameError: name 'car_pool_capacity' is not defined
用你自己的话解释一下这个错误信息,解释时记得使用行号,而且要说明原因。
更多的加分习题:
- 解释一下为什么程序里用了 4.0 而不是 4。
- 记住 4.0 是一个“浮点数”,自己研究一下这是什么意思。
- 在每一个变量赋值的上一行加上一行注解。
- 记住
=
的名字是等于(equal),它的作用是为东西取名。 - 记住
_
是下划线字符(underscore)。 - 将
python
作为计算器运行起来,就跟以前一样,不过这一次在计算过程中使用 变量名来做计算,常见的变量名有i
,x
,j
等等。
Common Student Questions
What is the difference between = (single-equal) and == (double-equal)? |
---|
The = (single-equal) assigns the value on the right to a variable on the left. The == (double-equal) tests if two things have the same value. You'll learn about this in Exercise 27. |
Can we write x=100 instead of x = 100 ? |
You can, but it's bad form. You should add space around operators like this so that it's easier to read. |
How can I print without spaces between words in print ? |
You do it like this: print "Hey %s there." % "you" . You will do more of this soon. |
What do you mean by "read the file backward"? |
Very simple. Imagine you have a file with 16 lines of code in it. Start at line 16, and compare it to my file at line 16. Then do it again for 15, and so on until you've read the whole file backward. |
Why did you use 4.0 for space_in_a_car ? |
It is mostly so you can then find out what a floating point number is and ask this question. See the Study Drills. |
Copyright (C) 2010 by
Author: Zed Shaw
Translator:Zander Wong