2-2-5 练习:变量和赋值运算符

2019-01-17  本文已影响0人  章佳翳_PMO

练习:赋值和修改变量

现在该你来使用变量了。这道练习的注释(以 # 开头的行)提供了创建和修改变量的说明。请在每条注释后面根据说明写一行代码。

注意,这段代码使用了科学记数法来定义很大的数字。4.445e8 等于 4.445 * 10 ** 8,也就是 444500000.0

# The current volume of a water reservoir (in cubic metres)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic metres)
rainfall = 5e6

# decrease the rainfall variable by 10% to account for runoff
rainfall = 5e6*0.9

# add the rainfall variable to the reservoir_volume variable
reservoir_volume = reservoir_volume + rainfall

# increase reservoir_volume by 5% to account for stormwater that flows
# into the reservoir in the days following the storm
reservoir_volume = reservoir_volume*1.05

# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume = reservoir_volume*0.95

# subtract 2.5e5 cubic metres from reservoir_volume to account for water
# that's piped to arid regions.
reservoir_volume = reservoir_volume - 2.5e5

# print the new value of the reservoir_volume variable
print(reservoir_volume)

更改变量

更改变量会如何影响到用该变量定义的另一个变量?我们来看一个示例。

这是关于山景城人口和人口密度的原始数据。

>>> mv_population = 74728
>>> mv_area = 11.995
>>> mv_density = mv_population/mv_area

现在我们重新定义 mv_population 变量:

注意:后续代码跟在上面三行代码后面,而非重新开始)

>>> mv_population = 75000

习题 2/3

思考一下上方的代码,下面的表达式输出会是什么?

>>> print(int(mv_density))    

习题 3/3

这是美国的州列表,按照加入联邦的日期排序。假设你想为特拉华州创建一个变量并赋一个值,表示它首先加入了联邦。以下哪些项是有效的 Python 变量名和赋值?

好好学习,天天向上

上一篇下一篇

猜你喜欢

热点阅读