[英]Python condition not applying (if/elif)
我的python代码中的条件有问题。 这是一个数学应用程序,这是部分代码无法正常运行:
def askNumber():
"""Asks the number to test"""
a=raw_input("Select the number to test (type 'exit' for leaving):")
if len(a)!=0 and a.lower!="exit":
try:
b= int(a)
processing(b)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
time.sleep(1)
askNumber()
elif len(a)!=0 and a.lower=="exit":
answer()
else:
print "Your input can't be 'empty'"
time.sleep(1)
askNumber()
因此,当在raw_input中输入“ a”时,我键入“ exit”,假定的适用条件是小数点,但最终应用if则结束,并显示“您的输入无效。请输入一个数字”! ” 抱歉,如果很明显,我是个乞讨人,尽管我尝试几次发现错误。
您需要调用 .lower()
函数。
if len(a) != 0 and a.lower() != "exit":
# ...
elif len(a) != 0 and a.lower() == "exit":
真正不需要测试len(a)!=0
,只需测试a
自身:
if a and a.lower() != "exit":
# ...
elif a and a.lower() == "exit":
空字符串在布尔上下文中的值为False
。
您的程序流程由内而外,我是否可以提出一些改进建议?
def askNumber():
"""Asks the number to test"""
while True:
a = raw_input("Select the number to test (type 'exit' for leaving):")
if not a:
print "Your input can't be 'empty'"
continue
if a.lower() == "exit":
answer()
break
try:
b = int(a)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
continue
processing(b)
实际上, not a
分支也可以消除(空输入将在中处理except
)。
您可以更改以下条件:
if a and a.lower() !="exit":
# .....
elif a and a.lower() == "exit":
answer()
elif a and not a.isdigit(): print "invalid input"
else:
#.............
请注意,您不需要len(a) != 0
,只需使用a
will可以评估它是否为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.