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