【问题标题】:Remove my last print line in a while loop在while循环中删除我的最后一个打印行
【发布时间】:2016-03-18 11:38:37
【问题描述】:

下面是我编写的一个函数,它完全按照我想要的方式工作。用户创建一个列表,然后最终吐出一个他们创建的没有负数的列表。我遇到的问题是在他们执行我的(-1 退出)后删除我的“人口无效,请输入一个高于 0 的值”。我希望用户能够输入 -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()

【问题讨论】:

    标签: python python-2.7 printing while-loop


    【解决方案1】:

    只需颠倒 2 个 if 的顺序

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

    【讨论】:

    • 谢谢!这么容易和简单的事情。对这一切都有点新意,所以我非常感谢!
    • @Phil 不客气,我们都必须从某个地方开始
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      你的问题是这个 if 语句:

      if user <= '0':
      

      改成这个

      if user &lt;= '0' and user != '-1':

      这样,-1 是唯一低于 0 的其他输入将被忽略。

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

      【讨论】:

      • 为什么我被否决了?我不明白,我的解决方案工作正常。
      猜你喜欢
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多