python04 变量和变量的命名

来源:互联网 发布:中国历年gdp数据图表 编辑:程序博客网 时间:2024/06/06 18:13

我的理解,变量和代数基本上是一个概念。

ex4.py

cars = 100space_in_a_car = 4.0drivers = 30passengers = 90cars_not_driven = cars - driverscars_driven = driverscarpool_capacity = cars_driven * space_in_a_caraverage_passengers_per_car = passengers / cars_drivenprint "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."

1-8行中的那些单词就是变量,同时可以看到,用=号来给变量赋值

稍微改下代码

space_in_a_car = 4drivers = 30passengers = 90cars_not_driven = cars - driverscars = 100cars_driven = driverscarpool_capacity = cars_driven * space_in_a_caraverage_passengers_per_car = passengers / cars_drivenprint "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."

然后运行一下:

从而猜测,变量如果未赋值是不能使用的

再改下代码

cars space_in_a_car = 4drivers = 30passengers = 90cars_not_driven = cars - driverscars_driven = driverscarpool_capacity = cars_driven * space_in_a_caraverage_passengers_per_car = passengers / cars_drivenprint "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."

果然。

至于NameError前的的单词 cars为什么会显示"锘缟ars",我也没弄明白,有知道的可以告诉我。