题解 | 牛牛的逻辑运算:与、或、非

牛牛的逻辑运算

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 中, 是逻辑运算符,分别用来进行逻辑运算。这些运算符在布尔值(TrueFalse)之间进行操作,常用于条件判断中。它们对应的符号分别是:

  1. 与(AND):用 and 表示
  2. 或(OR):用 or 表示
  3. 非(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 变为 FalseFalse 变为 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

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务