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

查看:29
本文介绍了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天全站免登陆