Skip to main content
 首页 » 编程设计

Python 2.7.2 if/or 意外行为

2025年05月04日12bonelee

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

希望对您有所帮助!提前致谢。

请您参考如下方法:

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

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