Skip to content

Latest commit

 

History

History
115 lines (85 loc) · 3.74 KB

17.md

File metadata and controls

115 lines (85 loc) · 3.74 KB

算术运算符

  • +
  • -
  • *
  • /
  • % 取余(相除后的余数)
  • ** 取幂(注意 ^ 并不执行该运算,你可能在其他语言中见过这种情形)
  • // 相除后向下取整到最接近的整数

算术运算符[相关练习]

  1. 在过去三个月的电费是 23 美元、32 美元和 64 美元。这三个月的每月平均电费是多少?

    print((23 + 32 + 64) / 3)
  2. 一个区域是宽 9 块砖,长 7 块砖,另一个区域是宽 5 块砖,长 7 块砖。一包砖有 6 块。问:(1)需要多少块砖?(2) 如果购买 17 包砖,每包有 6 块砖。剩下多少块砖?

    # Fill this in with an expression that calculates how many tiles are needed.
    print(9*7 + 5*7)
    
    # Fill this in with an expression that calculates how many tiles will be left over.
    print(17*6 - (9*7 + 5*7))

赋值运算符

reserved-words

注:图片来源网络

赋值运算符[相关练习]

题目 A: 这道练习的注释(以 # 开头的行)提供了创建和修改变量的说明。请在每条注释后面根据说明写一行代码。 [注意] 这段代码使用了科学记数法来定义很大的数字。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 *= 1-0.1
# add the rainfall variable to the reservoir_volume variable
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 *= 1+0.05
# decrease reservoir_volume by 5% to account for evaporation
reservoir_volume *= 1-0.05
# subtract 2.5e5 cubic metres from reservoir_volume to account for water
# that's piped to arid regions.
reservoir_volume -= 2.5e5
# print the new value of the reservoir_volume variable
print(reservoir_volume)

题目 B: 思考下面代码的输出:

# 这是关于山景城人口和人口密度的原始数据。
mv_population = 75000
mv_area = 11.995
mv_density = mv_population/mv_area
print(int(mv_density)) # 6252

布尔型运算符、比较运算符和逻辑运算符

  • 布尔数据类型存储的是值 TrueFalse,通常分别表示为 10

  • 通常有 6 个比较运算符会获得布尔值:

    符号使用情况 布尔型 运算符
    5 < 3 False 小于
    5 > 3 True 大于
    3 <= 3 True 小于或等于
    3 >= 5 False 大于或等于
    3 == 5 False 等于
    3 != 5 True 不等于
  • 需要熟悉的三个逻辑运算符

    逻辑使用情况 布尔型 运算符
    5 < 3 and 5 == 5 False and - 检查提供的所有语句是否都为 True
    5 < 3 or 5 == 5 True or - 检查是否至少有一个语句为 True
    not 5 < 3 True not - 翻转布尔值

布尔型运算符、比较运算符和逻辑运算符[相关练习]

  • 哪个地区人口密度更高?里约还是旧金山?
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5

san_francisco_pop_density = sf_population / sf_area
rio_de_janeiro_pop_density = rio_population / rio_area

# Write code that prints True if San Francisco is denser than Rio, and False otherwise
print(san_francisco_pop_density > rio_de_janeiro_pop_density) # False
  • 为何 Python 使用 == 检查是否相等,而不是 =
  • 因为 = 用来为变量赋值的