我想让CR或null被接受为零。
这是我用来验证条目是否为整数的代码,如果我键入0,它可以工作,但如果我只是按ENTER键,它就不接受它。
while True:
try:
Checkno = int(input("Enter Check number, if none Enter 0"))
#Checkno should be valid integer 0 is ok
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#Checkno was successfully parsed!
#we're ready to exit the loop.
break发布于 2020-12-12 04:05:15
问题是input()去掉了尾随的换行符。按Enter键将返回空字符串。您可以使用or的一个有趣的属性来解决这个问题。它将在第一个True事物上短路,并解析为该值。"foo" or "bar"是"foo",而"" or "bar"是"bar"。在您的示例中,
while True:
try:
Checkno = int(input("Enter Check number, or Enter for 0: ").strip() or 0)
#Checkno should be valid integer 0 is ok
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#Checkno was successfully parsed!
#we're ready to exit the loop.
break
print(f"using {Checkno}")https://stackoverflow.com/questions/65257814
复制相似问题