你已经学会了 print 和算术运算。下一步你要学的是“变量”。在编程中,变量只不过是用来指代某个东西的名字。程序员通过使用变量名可以让他们的程序读起来更像英语。而且因为程序员的记性都不怎么地,变量名可以让他们更容易记住程序的内容。如果他们没有在写程序时使用好的变量名,在下一次读到原来写的代码时他们会大为头疼的。
如果你被这章习题难住了的话,记得我们之前教过的:找到不同点、注意细节。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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) 字符。你要自己学会怎样打出这个字符来。这个符号在变量里通常被用作假想的空格,用来隔开单词。
$ 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.
$
当我刚开始写这个程序时我犯了个错误,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
用你自己的话解释一下这个错误信息,解释时记得使用行号,而且要说明原因。
更多的加分习题: