Python 2.7.2 if /或意外行为

时间:2011-12-26 22:07:38

标签: python logic

我正在学习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新手!

希望你能帮忙!提前谢谢。

2 个答案:

答案 0 :(得分:5)

raw_input返回时,您的number_of_lines变量是字符串。在与10:

比较之前,您需要将其转换为整数
not(number_of_lines.isdigit()) or int(number_of_lines) > 10

答案 1 :(得分:3)

我首先尝试将字符串转换为整数,如果他们输入其他内容,则会捕获错误。这也让你放弃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
相关问题