在Python中,`True` 和 `False` 是内置的布尔值,用于进行逻辑判断。以下是一些基本用法:
条件表达式
x = 5if x > 3:print("x大于3")else:print("x小于等于3")
循环语句
`for` 循环:
for i in range(5):print(i)
`while` 循环:
i = 0while i < 5:print(i)i += 1
布尔值测试
print(1 == 1) 输出:Trueprint(0 == 0) 输出:Trueprint("hello" == "hello") 输出:Trueprint("") == "" 输出:Trueprint([]) == [] 输出:Trueprint({}) == {} 输出:True
布尔值作为字典键 (在Python 3中,由于`True`和`False`是关键字,不能直接用作字典键,但可以用单引号或双引号括起来):

Python 3.xd = {'True': 'true', 'False': 'false'}Python 2.xd = {'True': 'true', 'False': 'false'}
布尔值的其他用法
`not` 关键字用于取反布尔值:
if not 0:print("非零值")
`and` 和 `or` 关键字用于组合布尔表达式:
if 1 > 0 and "hello" == "hello":print("两个条件都为真")
请注意,`True` 和 `False` 的大小写敏感,必须首字母大写
