在while循环中删除我的最后一个打印行

时间:2015-12-12 16:59:50

标签: python python-2.7 printing while-loop

下面是我写的一个功能,它完全按照我想要的方式工作。用户创建一个列表,然后最终吐出他们创建的没有负数的列表。我遇到的问题是删除我的“人口无效,请输入一个高于0的值”后执行我的(-1退出)。我希望用户能够输入-1,然后用其他任何东西吐出列表。那么有没有人对我的功能有任何提示?

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

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

您可以颠倒两个if语句的顺序:

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

答案 2 :(得分:-1)

你的问题是这个if语句:

if user <= '0':

更改为

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

这样,-1是0以下唯一会被忽略的其他输入。

或者如上所述,颠倒if语句的顺序。

相关问题