天天看點

《笨辦法學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關鍵字用作變量。

繼續閱讀