2015-12-12 141 views
1

下面是我寫的功能,它的工作方式與我想要的完全一致。用戶創建一個列表,然後最終吐出一個他們創建的沒有負數的列表。我遇到的問題是在他們執行我的(-1退出)後刪除我的「人口無效,請輸入一個高於0的值」。我希望用戶能夠輸入-1,然後再吐出沒有其他的列表。那麼有沒有人對我的功能有任何提示?刪除我在while循環中的最後一行打印

def getData(): 
    import math 
    pop = [] 
    while True: 
     user = raw_input("Please enter a population number (-1 to quit): ") 
     pop.append(user) 
     if user <= '0': 
      print "Population not valid, please input a value higher then 0" 
     if user == '-1': 
      break 
    new_pop = map(int, pop) 
    pop2 = filter(lambda x:x >=1, new_pop) 
    print "Your population list is: ", pop2  
getData() 

回答

1

只是反向的2 IFS

def getData(): 
    import math 
    pop = [] 
    while True: 
     user = raw_input("Please enter a population number (-1 to quit): ") 
     pop.append(user) 
     if user == '-1': 
      break 
     if user <= '0': 
      print "Population not valid, please input a value higher then 0" 
    new_pop = map(int, pop) 
    pop2 = filter(lambda x:x >=1, new_pop) 
    print "Your population list is: ", pop2  
getData() 
+0

謝謝!這樣一個簡單而簡單的事情。所有這一切都有點新,所以我非常感謝! – Phil

+0

@Phil歡迎您我們都必須從某處開始 – maazza

0

你可以翻轉你的兩個if語句的順序順序:

if user == '-1': 
     break 
    elif user <= '0': 
     print "Population not valid, please input a value higher then 0" 
-1

你的問題是這樣的if語句:

if user <= '0': 

改變這種

if user <= '0' and user != '-1':

這樣,-1低於0唯一的其他輸入將被忽略。

或如上所述,顛倒if語句的順序。

+0

爲什麼我會陷入低谷?我不明白,我的解決方案正常工作。 – abe

相關問題