2016-08-27 59 views
0

我已經堅持了幾天,但沒有任何幫助。無論我做什麼,最小的價值都不會改變。儘管它使用幾乎相同的代碼行,但它不會發生最大的值。如何使用if else語句更改變量的值?

smallest = None 
largest = None 
while True: 
    num = raw_input("Enter a number: ") 
    if num == "done": 
     break 
    try: 
     x = int(num) 
     if x < smallest: 
      smallest = x 
     elif x > largest: 
      largest = x 
    except: 
     print"Invalid input" 
     continue 
print "Maximum is", largest 
print "Minimum is", smallest 
+4

你不處理「最小」和/或「最大」仍然是「無」的情況。 – jonrsharpe

+0

在Python 2中,'None'小於任何其他數字。在Python 3中,將一個整數與None比較會導致錯誤。 – Barmar

+0

第一次爲最小和最大變量分配輸入值 –

回答

1

首先,(幾乎)從來沒有使用裸except聲明。你會發現你不能或不想處理的異常(如SystemExit)。至少,請使用except Exception

其次,您的except區塊意味着您只想處理int(num)可能引起的ValueError。趕上,沒有別的。

第三,比較xsmallestlargest是獨立的ValueError處理,所以移動,走出try塊到try/except語句後的代碼。

smallest = None 
largest = None 
num = "not done" # Initialize num to avoid an explicit break 
while num != "done": 
    num = raw_input("Enter a number: ") 
    try: 
     x = int(num) 
    except: 
     print "Invalid input" 
     continue 

    if smallest is None: 
     smallest = x 
    if largest is None: 
     largest = x 

    if x < smallest: 
     smallest = x 
    elif x > largest: 
     largest = x 

print "Maximum is", largest 
print "Minimum is", smallest 

請注意,您不能摺疊None支票轉換爲if/elif說法,因爲如果用戶只輸入一個號碼,你需要確保smallestlargest被設定爲這一數字。 之後輸入第一個數字,不存在單個數字將同時更新smallestlargest的情況,因此if/elif有效。

4

的問題是,你是,在這兩種情況下,在第一次迭代比較數字來None。在Python 2中,與None相比,每個數字都會顯示爲「更大」,因此代碼適用於查找最大值,但無法找到最小值。

順便說一句,在Python 3中,同樣會給你一個TypeError

要修復它,您可以比較改變這樣的事情,走的是None情況考慮:

if smallest is None or x < smallest: