Python - How to break while loop after empty value in a int turning input? [duplicate]

大城市里の小女人 提交于 2020-07-04 03:21:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!