首页 > 解决方案 > 清理 try 和 except 语句

问题描述

嗨,我正在制作一个代码,用户需要在其中输入一个 0-255 之间的数字,所以我希望尝试使用,除非他们输入一个字母和一个 if 语句,如果他们在外面输入一个数字0-255。我写的没有错误,但看起来很乱,因为我必须两次调用输入等等。任何想法如何清理它/使它更短更容易阅读。

    try:
        user_input = int(input('Enter a number between 0 and 255 to be converted to 8-bit binary: '))
        if user_input > 0 and user_input < 255:
            break
        else:
            user_input = int(input('\nEnter a number between 0 and 255 to be converted to 8-bit binary: '))
    except:
        print ('\nPlease enter a valid number.')

标签: pythonpython-3.xwhile-looptry-except

解决方案


在 python 中,try/except 是关于处理异常的。在您的代码中,我没有看到任何异常被引发。使用 while 循环来确保用户输入有效数字怎么样?就像是:

while True:
    user_input = int(input('Enter a number between 0 and 255 to be converted to 8-bit binary: '))
    if user_input > 0 and user_input < 255:
        break
    else:
        print ('\nPlease enter a valid number.')

推荐阅读