练习代码
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_passenger_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_passenger_per_car, "in each car.")
Study Drills
When I wrote this program the first time I had a mistake, and Python told me about it like this:
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
Explain this error in your own words. Make sure you use line numbers and explain why.
因为变量名打错了。
Here are more study drills:
- I used 4.0 for space_in_a_car, but is that necessary? What happens if it’s just 4?
没必要。因为车的座位数只能是整数。改成4之后,
carpool_capacity
也会变成整数。
-
Remember that 4.0 is a floating point number. It’s just a number with a decimal point, and you need 4.0 instead of just 4 so that it is floating point.
-
Write comments above each of the variable assignments.
cars = 100 # 轿车 100 辆
space_in_a_car = 4 # 每辆车载客量 4 人
drivers = 30 # 司机 30 人
passengers = 90 # 乘客 90 人
cars_not_driven = cars - drivers # 没人驾驶的车 = 车数 - 司机数
cars_driven = drivers # 有人驾驶的车 = 司机数
carpool_capacity = cars_driven * space_in_a_car # 可运载量 = 有人驾驶的车 * 每辆车的载客量
average_passenger_per_car = passengers / cars_driven # 每辆车上平均载客量 = 乘客数 / 有人驾驶的车辆
# 打印
print("There are", cars, "cars avilable.")
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_passenger_per_car, "in each car.")
-
Make sure you know what = is called (equals) and that its purpose is to give data (numbers, strings, etc.) names (cars_driven, passengers).
-
Remember that _ is an underscore character.
-
Try running python3.6 from the Terminal as a calculator like you did before, and use variable names to do your calculations. Popular variable names include i, x, and j.
网友评论