带有Python示例的 or 关键字

Python或关键字

or是python中的关键字(区分大小写),实际上是一个逻辑运算符,用于验证多个条件。它类似于C,C++编程中的逻辑或(^)算子。它至少需要两个条件并返回True–如果一个或多个条件为True。

“or”关键字/运算符的真值表

Condition1	Condition2	(Condition1 or Condition2)
True		True		True 
True 		False		True
False		True		True
False 		False		False

or关键字/运算符的语法:

    condition1 or condition2

示例

    Input:
    a = 10
    b = 20

    # 条件
    print(a>=10 or b>=20)
    print(a>10 or b>20)

    Output:
    True
    False

or运算符的Python示例

例1:取两个数字并使用or运算符测试条件

# python代码演示示例
# 或关键字/运算符

a = 10
b = 20

# 打印返回值
print(a>=10 or b>=20)
print(a>10 or b>20)
print(a==10 or b==20)
print(a==10 or b!=20)

输出结果

True
False
True
True

示例2:输入一个数字并检查它是否可以被2或3整除

# 输入数字并检查是否 
# 它可以被2或3整除

# 输入 
num = int(input("Enter a number: "))

# 检查num被2或3整除
if num%2==0 or num%3==0:
    print("Yes, ", num, " is divisble by 2 or 3")
else:
    print("No, ", num, " is not divisble by 2 or 3")

输出结果

First run:
Enter a number: 66
Yes,  66  is divisble by 2 or 3

Second run:
Enter a number: 5
No,  5  is not divisble by 2 or 3

示例3:输入一个字符串并检查它是“ Hello”还是“ World”

# 输入 a string and check 
# 无论是“你好”还是“世界”"Hello" or "World"

# 输入
string = input("Enter a string: ")

# 检查条件
if string=="Hello" or string=="World":
    print("Yes, \"", string, "\" is either \"Hello\" or \"World\"")
else:
    print("No, \"", string, "\" is neither \"Hello\" nor \"World\"")

输出结果

First run:
Enter a string: Hello
Yes, " Hello " is either "Hello" or "World"

Second run:
Enter a string: World
Yes, " World " is either "Hello" or "World"

Third run:
Enter a string: nhooo
No, " nhooo " is neither "Hello" nor "World"