[root@lc test]# 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 in each car.
[root@lc test]#
更多的加分习题:
1.我在程序里用了 4.0 作为 space_in_a_car 的值,这样做有必要吗?如果只用 4 会有什么问题?
个人觉得没有必要,改成4试了一下,没有发现什么问题。
[root@lc test]# vi ex4-1.py
cars = 100
space_in_a_car = 4
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, "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."
"ex4-1.py" 15L, 556C written
[root@lc test]#
运行该程序,得到结果:
[root@lc test]# python ex4-1.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 in each car.
[root@lc test]#
2.记住 4.0 是一个“浮点数”,自己研究一下这是什么意思。
3.在每一个变量赋值的上一行加上一行注解。
[root@lc test]# vi ex4-3.py
#define space_in_a_car as 4.0
#define cars as 100
cars = 100
#define space_in_a_car as 4.0
space_in_a_car = 4.0
#define drivers as 30
drivers = 30
#define passengers as 90
passengers = 90
#define cars_not_driven as cars - drivers,the result is 100 - 30 = 70
cars_not_driven = cars - drivers
#define cars_driven as as drivers ,the result is 30
cars_driven = drivers
#define carpool_capacity as cars_driven * space_in_a_car,the result is 30 * 4.0 = 120.0
carpool_capacity = cars_driven * space_in_a_car
#define average_passengers_per_car as passengers / cars_driven,the result is 90 / 30 = 3
average_passengers_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_passengers_per_car, "in each car."
"ex4-3.py" 23L, 954C written
[root@lc test]#
4.记住 = 的名字是等于(equal),它的作用是为东西取名。
5.记住 _ 是下划线字符(underscore)。
6.将 python 作为计算器运行起来,就跟以前一样,不过这一次在计算过程中使用变量名来做计算,常见的变量名有 i, x, j 等等。
[root@lc test]# vi ex4-6.py
i = 10
j = 100
k = i + j
print "i =", i
print "j =", j
print "k =", k
print "i + j =", i + j
print "j - i =", j - i
print "i * j =", i * j
"ex4-6.py" 11L, 141C written
[root@lc test]#
运行该程序:
[root@lc test]# python ex4-6.py
i = 10
j = 100
k = 110
i + j = 110
j - i = 90
i * j = 1000
[root@lc test]#
至此,Python这一小节的学习结束了。