在 If 语句中使用逻辑运算符不会输出预期的结果

Using logical operators with If statements won't output what is expected

开始学习了Python写了这个:


num1 = int(input('First number '))
num2 = int(input('second number '))
num3 = int(input('third number '))

if num1 > (num2 and num3):
    print(f'{num1:2} is bigger')
    if num2 > num3:
        print(f'{num3:2} is smaller')
    if num3 > num2:
        print(f'{num2:2} is smaller')

if num2 > (num1 and num3):
    print(f'{num2:2} is bigger')
    if num1 > num3:
        print(f'{num3:2} is smaller')
    if num3 > num1:
        print(f'{num1:2} is smaller')
    

if num3 > (num1 and num2):
    print(f'{num3:2} is bigger')
    if num1 > num2:
        print(f'{num2:2} is smaller')
    if num2 > num1:
        print(f'{num1:2} is smaller')

如果我为第一个数字输入“5”,第二个数字为“4”,第三个数字为“2” 它输出:

"5 is bigger
 2 is smaller
 4 is bigger
 2 is smaller"

他为什么读条件语句为假的那一行?

我错过了什么?

另一种写法是:

"if num2 > (num1 and num3) and (num1 < num3):
    #print(f'{num2:2} is bigger and {num1:2} is smaller')"

但也没有用。

谢谢大家

num1 > (num2 and num3)

这并不像你想象的那样有效,你需要这样的东西:

num1 > num2 and num1 > num3

# Or if there's lots of them:
num1 > max(num2, num3, num4, num5)

您当前的方法首先计算 num2 and num3,如果它为假,则给您 num2(见下文),否则为 num3。所以3 > (4 and 2)3 > 2是一样的,因为4 and 22。以下文字记录说明了这一点:

>>> print(0 and 99)
0
>>> print(1 and 99)
99
>>> print(2 and 99)
99
>>> print(-1 and 99)
99

基本上,如果数字为零,则数字被认为是假的,因此输出如上所示。


顺便说一句,您可能还想想想如果两个或多个数字相等会发生什么。

num1 > (num2 and num3)

这东西没有按照您想要的方式工作。 您需要将条件分开,然后在其中添加“和”。它应该看起来像这样。

num1 > num2 and num1 > num3

此外,在您编写的代码中从未使用过 elifelse,这很方便。使用它可以减少一些条件和歧义。

num1 = int(input('First number '))
num2 = int(input('second number '))
num3 = int(input('third number '))

if num1 > num2 and num1 > num3:
    print(f'{num1:2} is bigger')
    if num2 > num3:
        print(f'{num3:2} is smaller')
    else: # as num2 > num3 is not true, then the opposite one should be true
        print(f'{num2:2} is smaller')

elif num2 > num1 and num2 > num1:
    print(f'{num2:2} is bigger')
    if num1 > num3:
        print(f'{num3:2} is smaller')
    else:
        print(f'{num1:2} is smaller')
    
elif num3 > num1 and num3 > num2:
    print(f'{num3:2} is bigger')
    if num1 > num2:
        print(f'{num2:2} is smaller')
    else:
        print(f'{num1:2} is smaller')