Published 7月 26, 2018 by with 0 comment

習題4 - 變量和命名




用Notepad++打下列的程式碼,
另存為ex4.py.
cars = 100
space_in_a_car = 4.0
drivers = 30
passagers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passagers_per_car = passagers / 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", passagers, "to carpool today.")
print ("We need to put about", average_passagers_per_car, "in each car.")

然後用Windows的cmd, 執行python打開它.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW

C:\Users\Peter\Desktop\Python\LP3THW>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.0 people today.
We have 90 to carpool today.
We need to put about 3.0 in each car.

C:\Users\Peter\Desktop\Python\LP3THW>

完成

修改Line 2, 把他改成整數(int)4
則結果的Lline 5, 由原本的浮點數(Float)120.0, 變成整數(int)120
或者新增Line 17, 嘗試將變量做運算後, 列印出來.
cars = 100
space_in_a_car = 4
drivers = 30
passagers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passagers_per_car = passagers / 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", passagers, "to carpool today.")
print ("We need to put about", average_passagers_per_car, "in each car.")
print ("##test##", cars * space_in_a_car, "##test##")

結果
C:\Users\Peter\Desktop\Python\LP3THW>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.
##test## 400 ##test##

C:\Users\Peter\Desktop\Python\LP3THW>

後記
這習題主要是學習將某個變量名套用數值(car = 100)
然後進一步列印這些變量運算後的結果(print ("We can transport", carpool_capacity, "people today."))


最初發表 / 最後更新: 2018.07.26 / 2018.07.26

0 comments:

張貼留言