[英]Python 2.7.2 if/or unexpected behaviour
我目前正在学习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
我会尝试首先将字符串转换为整数,如果它们放入其他内容,则会捕获错误。 这也让您放弃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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.