定义变量,并在print里输出变量的值
我们已经能用 print 输出点东西和做点计算,下一步我们要学习变量。
在python里,变量就是一个名字,一个标签。
开始打代码
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, "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.")
What you should see
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.
Study Drill
当我第一次输入这段代码时出现了错误:
Traceback (most recent call last):
File "ex4.py", line 8, in <module>
average_passengers_per_car = car_pool_capacity / passenger
NameError: name 'car_pool_capacity' is not defined
解释一下这是什么错误?
My answer:
line 8,告诉我们错误在第8 行的< < “average_passengers_per_car = car_pool_capacity / passenger” >> 这段代码中;
NameError:name ‘car_pool_capacity’ is not defined:告诉我们变量 car_pool_capacity 并没有被定义,解决方法,定义一个变量 car_pool_capacity 即可
1、space_in_a_car = 4.0 这一行,用浮点数是否必要?如果只是用 4 会怎样?
2、记住4.0是一个浮点数。数字加个小数点,就能进行浮点数的运算了。
3、给每一行添加注释
4、确实理解“ = ”的含义。它的作用是给数据(数字,字符串等)名字。
5、记住 “_" 是下划线字符。
6、尝试用python作为计算器进行计算,用上流行的变量名:i , x, and j。
>>> i = 1
>>> j = 2
>>> x = i + j
>>> print((x + i) / j)
2.0 # 除法返回浮点数