2017-08-05 17 views
1

試圖學習Python。在這個幾個小時。阻礙練習5.2

我想要做的是輸入幾個數字(例如7,4,6,10,& 2),然後打印最大值和最小值。 我的代碼完美適用於我輸入的每個數字1-9。一旦我達到10或更高,它就會變得不穩定。 它看起來是10讀爲1,零附着它,它說10是最小值。 我在哪裏錯了? 。 練習是輸入幾個數字,然後打印最大值和最小值。我的代碼完美適用於我輸入的每個數字1-9。一旦我達到10或更高,它會變得不穩定,並列出10個最低限度。 我在哪裏錯了? 。

largest = None 
smallest = None 
the_list = [] 

while True: 
    num = input('Enter a number or done: ') 

    #Handle the edge cases 
    if num == 'done' : break 
    if len(num) < 1 : break # Check for empty line 

    # Do the work 
    try : 
     number = int(num) 
     the_list.append(num) 
    except: 
     print("Invalid input") 
     #continue 

print(the_list) # NOTE: This is new so I can see what is in the_list 

for value in the_list: 
    if smallest is None: 
     smallest = value 
    elif value < smallest: 
     smallest = value 

for the_num in the_list: 
    if largest is None: 
     largest = value 
    elif the_num > largest: 
     largest = value #the_num 

print("Maximum is", largest) 
print("Minimum is", smallest) 
+0

'min'和'max'功能存在的原因,btw :) –

+0

是的,謝謝你迴應亞當。我會在不同情況下記住這一點。這項任務比我分享的要多,所以在這種情況下我不能那麼簡單。 –

回答

1

你居然不追加number到列表中,但你追加num到列表中(一個簡單的拼寫錯誤,我相信)。因此,你永遠不會追加一個int到列表中,但str。顯然,這將在以後產生問題,當你比較字符串,如:

>>> '10' < '3' 
True 

變化the_list.append(num)the_list.append(number)


另一個錯誤是,在你的第二個for循環中,您忘了改valuethe_num

+1

請注意,這仍然不會使代碼正確,因爲他正在迭代'the_num',但是當他發現最大數字 –

+0

時,比較和調整'value'謝謝您的評論。將「the_list.append(number)」和「value」更改回「the_num」的技巧。我首先看到了彼得的迴應。再次感謝。 –

0

問題是您將字符串追加到列表中,而不是整數。也就是說,你的列表包括以下的現在(如果您輸入2,然後10:

the_list = ['2', '10']

由於串字典順序比較,「10」小於「2」,因爲「1」是小於「2」。你想要做什麼是追加整數。

try : 
    number = int(num) 
    the_list.append(number) 
except: 
    print("Invalid input") 
    #continue 

這樣一來,你會比較數的數值,你會得到正確的答案!

+0

彼得這樣做了。非常感謝。我懷疑我可能會將數字條目添加爲字符串,但不確定如何檢查。那將是我下一個研究的領域。 –