如果声明没有评估所有条件并执行

问题描述:

好吧,所以我是新来的python,并试图学习如何编码。今天我遇到了一个我不明白的问题。因此,该代码按预期执行,并打印三个数字中最大的一个,而不管最大数字的位置。如果声明没有评估所有条件并执行

if num1 >= num2 and num3: 
     print(num1, 'Is the greatest number!') 

    elif num2 >= num3 and num1: 
     print(num2, 'Is the greatest number!') 

    else: 
     print(num3, 'Is the greatest number') 

但是,如果我改变elif的语句是:

elif num2 >= num1 and num3: 
     print(num2, 'Is the greatest number!') 

即使NUM3是最大else语句将不执行,它会显示NUM1 NUM2或较大的数量。

+0

尝试使用'num1 = 2','num2 = 1'和'num3 = 10'运行,代码的第一个代码段将不起作用。它会打印“(2,'最大的数字!')”。 – Jae

这里的问题是在这样的关键词and作品的误解。

在python中,and用于分隔两个完整的逻辑语句:cond1 and cond2。它首先检查cond1。如果cond1True,则继续检查cond2。如果cond2也是True,则整个语句评估为True

当你做if num1 >= num2 and num3,你实际上是在问蟒蛇如果以下True

  1. num1 >= num2
  2. num3存在,且不能0(因为它是一个数字)

这是不是检查if num1 >= num2 and num1 >= num3

因此,如果num1 = 2, num2 = 1, num3 = 3,您的条件仍然会返回 True

相同的概念适用于您的问题条件。

+1

'num3'存在且不是**零**(因为这些是数字)。 – alexis

+0

@alexis好点,我会改变这一点 – xgord

你的第一个版本纯粹是巧合。你需要做的

if num1 >= num2 and num1 >= num3: 
    print(num1, 'Is the greatest number!') 

elif num2 >= num3 and num2 >= num1: 
    print(num2, 'Is the greatest number!') 

else: 
    print(num3, 'Is the greatest number') 

虽然,这仍然将打印错误信息,如果任何一个数字都是平等的