2015-09-29 23 views
2

嘿,我被困在練習的一部分。我應該做的是要求一個數字(練習說我需要輸入數字(4,-3,-15,0,10,22,-9999),-9999是破號。 。使3所列出清單輸入所有數字,列表p都是正數且N爲所有負數這是我的代碼至今:在Python中詢問數字並返回列表

a = [] 
p = [] 
n = [] 
total = -9999 

while(True): 
    user_input = int(input('Please enter a number:')) 
    if(user_input == -9999): 
    break 
elif(user_input >= 0): 
    p.append(user_input) 
elif(user_input <= 0): 
    n.append(user_input) 


a = p + n 
print('The list of all numbers entered is:', '\n', a) 

,當我運行這個程序,並使用這些我得到的數字[4,0,10,22,-3,-15]這是正確的,但是當我查看這個練習的答案時,它的數字以不同的順序[4,-3,-15,0, 10,22]。我被困在如何獲得這個順序的數字

另一個快速的問題在本練習的第二部分,我應該找到平均所有數字,正數和負數。當我打印a,p,n時,它不會將0添加到負數列表中,即使我的user_input < = 0會拋出平均值。我錯過了什麼?

謝謝你們。

+0

更好地發佈練習題,因爲它可以讓我們清楚地理解問題。 – Mangesh

回答

1

對於第一部分使用這種

while(True): 
    user_input = int(input('Please enter a number:')) 
    if(user_input == -9999): 
     break 
    elif(user_input >= 0): 
     p.append(user_input) 
    elif(user_input <= 0): 
     n.append(user_input) 
    #always append to a, makes the order the same as input order. 
    a.append(user_input) 

(該identation問題是不好複製粘貼我假設) 對於第二部分可以使ELIF這樣,使之成爲0

工作
elif(user_input >= 0): 
     p.append(user_input) 
    if(user_input <= 0 and user_input != -9999): 
     n.append(user_input) 

它失敗的原因是因爲一旦它存儲在p中,它將跳過剩餘的elif else塊。

0

您的縮進是錯誤的編碼。結果,這兩個ELIF語句不在while循環中運行。嘗試下面的代碼。

a = [] 
p = [] 
n = [] 
total = -9999 

while(True): 
    user_input = int(input('Please enter a number:')) 
    if(user_input == -9999): 
    break 
    elif(user_input >= 0): 
     p.append(user_input) 
    elif(user_input <= 0): 
     n.append(user_input) 


a = p + n 
print('The list of all numbers entered is:', '\n', a)