True 在 Python 中,True 关键字用于表示布尔值 True。
True 关键字通常用于 if 语句中,在某个条件为真时执行一段代码。例如:
if condition:
# 当条件为真时执行的代码True 关键字还可以用于逻辑操作,如 and、or 和 not。例如:
if condition1 and condition2:
# 当 condition1 和 condition2 都为真时执行的代码
if condition1 or condition2:
# 当 condition1 或 condition2 为真时执行的代码
if not condition:
# 当条件为假时执行的代码True 关键字还可以用于比较,检查某个条件是否为真。例如:
if x > y:
# 当 x 大于 y 时执行的代码
if x == y:
# 当 x 等于 y 时执行的代码
if x != y:
# 当 x 不等于 y 时执行的代码使用 True 关键字的语法如下:
True在上述代码中,True 是一个关键字,不应分配给变量或修改。
下面是一个演示 True 关键字用法的示例:
x = 5
y = 10
if x < y:
print("x is less than y") # 输出:x is less than y
if x == y:
print("x is equal to y")
if not (x > y):
print("x is not greater than y") # 输出:x is not greater than y在上述代码中,第一个 if 语句为真,因为 x 小于 y。
第二个 if 语句为假,因为 x 不等于 y。第三个 if 语句为真,因为 x 不大于 y。
True 关键字区分大小写。