天天看点

《笨办法学python3-Learn Python 3 the HARD WAY》-习题4 变量和命名

学习内容:

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, "dirvers 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.")
           

运行结果:

《笨办法学python3-Learn Python 3 the HARD WAY》-习题4 变量和命名

知识点:

  1. 给每一行用"#"加注释
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.")# 打印  变量 cars
print ("There are only", drivers, "dirvers available.")# 打印  变量 drivers
print ("There will be", cars_not_driven, "empty cars today.")# 打印  变量 cars_not_driven
print ("We can transport", carpool_capacity, "people today.")# 打印  变量
print ("We have", passengers, "to carpool today.")# 打印  变量 carpool_capacity,
print ("We need to put about", average_passengers_per_car, "in each car.")# 打印  变量 average_passengers_per_car

           
  1. =(单等号)和==(双等号)的不同

    =: 将右边的值赋给左边的变量名。

    ==:检查左右两边的值是否相等。

  2. 变量(variable)的命名规则

    ①长度不受限,字符只能为字母、数字、下划线( _ )。注:不能有空格

    ②变量的第一个字符不能是数字。

    ③Python区分大小写。

    ④不能将Python关键字用作变量。

继续阅读