《笨办法学Python3》练习四:变量和命名

练习代码

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 
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:

  1. I used 4.0 for space_in_a_car, but is that necessary? What happens if it’s just 4?

没必要。因为车的座位数只能是整数。改成4之后,carpool_capacity也会变成整数。

  1. 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.

  2. 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.")
  1. Make sure you know what = is called (equals) and that its purpose is to give data (numbers, strings, etc.) names (cars_driven, passengers).

  2. Remember that _ is an underscore character.

  3. 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.

你可能感兴趣的:(《笨办法学Python3》练习四:变量和命名)