练习4--变量和命名

1 变量定义的方式: 变量名 = 变量的值

2 变量命名技巧

  •     用相对应的英文单词命名可以使得代码更加容易阅读;
  •     可用下划线“_”将变量名中不同的部分串起来;

3 扩展内容

  •     在赋值符号“=”两边加空格可以使代码看起来更加整齐漂亮;
  •     一个常见的错误警告“NameError : name ' car_pool_capacity ' is not defined”表示该变量没有被定义,原因可能是在输变量名的时候输错了。
  •    = 和 == 有什么区有什么区别? = 是把右边的值赋给左边的变量。 == 用来检测左右两边的东西是不是有同样的值。

4 举例

cars = 100                                                                                    # 定义变量cars表示可用车辆的个数
space_in_a_car = 4.0                                                                  # 定义变量space_in_a_car表示一辆车可载人数
drivers = 30                                                                                  # 定义变量drivers表示可用的司机的人数
passengers = 90                                                                          # 定义变量passengers表示乘客的人数
cars_not_driven = cars - drivers                                                  # 定义cars_not_driven表示不需要使用的车辆的个数,即空车数
cars_driven = drivers                                                                   # 定义cars_driven表示需要使用的汽车的个数
carpool_capacity = cars_driven * space_in_a_car                      # 定义变量carpool_capacity表示一共可以拼车的人数
average_passengers_per_car = passengers/cars_driven          # 定义变量average_passengers_per_car表示实际每辆车需要搭载的乘客人数
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.")

5 运行结果:

PS E:3_work4_python2_code2_LearnPythonTheHardWay> 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 people today.
We have 90 to carpool today.
We need to put about 3.0 in each car.
PS E:3_work4_python2_code2_LearnPythonTheHardWay>
原文地址:https://www.cnblogs.com/luoxun/p/13083850.html