【问题标题】:Python 2.7.2 if/or unexpected behaviourPython 2.7.2 如果/或意外行为
【发布时间】:2011-12-26 22:07:38
【问题描述】:

我目前正在学习 Python,但遇到了一个问题。 观察这段代码:

while 1:
    print "How many lines do you want to add to this file?"

    number_of_lines = raw_input(">").strip()

    if not(number_of_lines.isdigit()) or number_of_lines > 10:
        print "Please try a number between 1 and 10 inclusive."
        continue

代码要求用户输入一个数字,并检查它的有效性。但是由于某种原因,代码总是显示错误,即使用户确实输入了小于 10 的有效数字。

我可能在某个地方犯了一个小错误,但我想不通……作为一个 python 新手!

希望您能提供帮助!提前致谢。

【问题讨论】:

  • 仅供参考,一般情况下您应该使用try...except:口号是 EAFP 而不是 LBYL。
  • @katrielalex 谢谢,我以后会考虑这个,但我还没有那么深入。

标签: python logic


【解决方案1】:

当从raw_input 返回时,您的number_of_lines 变量是一个字符串。与 10 比较之前需要将其转换为整数:

not(number_of_lines.isdigit()) or int(number_of_lines) > 10

【讨论】:

    【解决方案2】:

    我会先尝试将字符串转换为整数,如果他们放入其他内容,则捕获错误。这也让你放弃isdigit 电话。像这样:

    while 1:
        print "How many lines do you want to add to this file?"
    
        try:
            number_of_lines = int(raw_input(">").strip())
        except ValueError:
            print "Please input a valid number."
            continue
    
        if number_of_lines > 10:
            print "Please try a number between 1 and 10 inclusive."
            continue
    

    【讨论】:

    • 感谢您的回答。下次我会考虑这个,但我想避免使用 try/except 因为我还是个新手,还没有那么远!不过,我赞成你的回答。
    猜你喜欢
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多