问题
I want to make the while loop break when empty input is typed. I know that the error is due to the int function because it cant turn to integer an empty input but how can i do what i'm trying to write?
while True:
numb = int(input("number"))
if numb % 2 == 0:
print("this number is even")
elif numb % 2 != 0:
print("this number is odd")
elif numb == '':
break
回答1:
This would work:
while True:
try:
numb = int(input("number"))
except ValueError:
break
if numb % 2 == 0:
print("this number is even")
elif numb % 2 != 0:
print("this number is odd")
Just handle the exception if the input cannot be converted into an integer. Now, any input that is not an integer would terminate the loop.
来源:https://stackoverflow.com/questions/41299440/python-how-to-break-while-loop-after-empty-value-in-a-int-turning-input