首页 › Python 3 教程 › 运算符
运算符
算术运算符
a, b = 17, 5
print(a + b) # 22
print(a - b) # 12
print(a * b) # 85
print(a / b) # 3.4 除法结果总是浮点数
print(a // b) # 3 整除
print(a % b) # 2 取余
print(a ** 2) # 289 乘方
比较运算符
==、!=、>、<、>=、<=,结果是布尔值。Python 支持链式比较:
x = 7
print(1 < x < 10) # True
逻辑运算符
and、or、not。它们是短路求值的:and 左边为假时不再计算右边。
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("可以入场")
赋值运算符
+=、-=、*= 等是简写:count += 1 等价于 count = count + 1。
成员与身份运算符
fruits = ["apple", "banana"]
print("apple" in fruits) # True
print("pear" not in fruits) # True
x = None
print(x is None) # 判断 None 应使用 is
== 比较值是否相等,is 比较是不是同一个对象。日常判断相等用 ==,判断 None 用 is。
练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 给定秒数 100000,换算成"天 时 分 秒"的形式。
查看参考答案
total = 100000
days, rest = divmod(total, 86400)
hours, rest = divmod(rest, 3600)
minutes, seconds = divmod(rest, 60)
print(f"{days} 天 {hours} 时 {minutes} 分 {seconds} 秒")参考输出:
1 天 3 时 46 分 40 秒练习 2 判断一个年龄 age 是否在 18 到 60 之间(包含两端),用一个链式比较完成。
查看参考答案
for age in [17, 18, 35, 60, 61]:
print(age, 18 <= age <= 60)参考输出:
17 False
18 True
35 True
60 True
61 False