你已經(jīng)學(xué)會了 print 和算術(shù)運(yùn)算。下一步你要學(xué)的是“變量”。在編程中,變量只不過是用來指代某個東西的名字。程序員通過使用變量名可以讓他們的程序讀起來更像英語。而且因?yàn)槌绦騿T的記性都不怎么地,變量名可以讓他們更容易記住程序的內(nèi)容。如果他們沒有在寫程序時使用好的變量名,在下一次讀到原來寫的代碼時他們會大為頭疼的。
如果你被這章習(xí)題難住了的話,記得我們之前教過的:找到不同點(diǎn)、注意細(xì)節(jié)。
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) 字符。你要自己學(xué)會怎樣打出這個字符來。這個符號在變量里通常被用作假想的空格,用來隔開單詞。
$ 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.
$
當(dāng)我剛開始寫這個程序時我犯了個錯誤,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
用你自己的話解釋一下這個錯誤信息,解釋時記得使用行號,而且要說明原因。
更多的加分習(xí)題: