Python-如何在int转换输入为空值后中断while循环? [英] Python - How to break while loop after empty value in a int turning input?

查看:499
本文介绍了Python-如何在int转换输入为空值后中断while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在键入空输入时使while循环中断. 我知道错误是由于int函数引起的,因为它无法将空的输入变成整数,但是我该怎么做呢?

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

推荐答案

这将起作用:

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.

这篇关于Python-如何在int转换输入为空值后中断while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆