题解 | 牛牛的逻辑运算:与、或、非
牛牛的逻辑运算
https://www.nowcoder.com/practice/d1f6b7dd048f48c58d974553f0c5a3bc
x,y = map(int,input().split(" ")) print(x and y) print(x or y) print(not x) print(not y)
在 Python 中,与、或 和 非 是逻辑运算符,分别用来进行逻辑运算。这些运算符在布尔值(True
或 False
)之间进行操作,常用于条件判断中。它们对应的符号分别是:
- 与(AND):用
and
表示 - 或(OR):用
or
表示 - 非(NOT):用
not
表示
1. and
(与)
and
运算符只有在两个条件都为 True
时才返回 True
,否则返回 False
。
a = True b = False result = a and b # False,因为 b 是 False print(result)
2. or
(或)
or
运算符只要有一个条件为 True
,就会返回 True
,只有两个条件都为 False
时才返回 False
。
a = True b = False result = a or b # True,因为 a 是 True print(result)
3. not
(非)
not
运算符是对布尔值进行取反,True
变为 False
,False
变为 True
。
a = True b = False result_a = not a # False result_b = not b # True print(result_a, result_b)
示例:组合使用
你也可以将这些运算符结合起来使用:
x = True y = False z = True result = (x and y) or not z # (True and False) or not True => False or False => False print(result)
这些逻辑运算符在进行条件判断时非常有用,比如在 if
语句中:
age = 20 is_student = True if age >= 18 and is_student: print("你是成年学生") else: print("你不是成年学生")
True和False的其他表示方式:
True:任何非0整数,常用1
False:0