2016-07-07 67 views
-2

好吧,所以我是新來的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

回答

1

這裏的問題是在這樣的關鍵詞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

2

你的第一個版本純粹是巧合。你需要做的

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') 

雖然,這仍然將打印錯誤信息,如果任何一個數字都是平等的