2011-12-26 51 views
1

我正在学Python,并且遇到了问题。 遵守本守则:Python 2.7.2如果/或意外的行为

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新手!

希望你能帮助!提前致谢。

+0

FYI一般你应该使用'try ... except':口号是EAFP不是LBYL。 – katrielalex 2011-12-27 00:45:05

+0

@katrielalex谢谢,我会在将来考虑这一点,但我还没有那么深入。 – Kieran 2011-12-27 13:12:39

回答

5

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

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

谢谢,这个解决方案的工作原理正是我所追求的! – Kieran 2011-12-26 22:23:10

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 
+0

谢谢你的回答。我将在下一次考虑这一点,但我想避免使用try/except,因为我仍然是一个新手,还没有那么远!尽管我已经提出了你的答案。 – Kieran 2011-12-26 22:24:13