Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 清理try和except语句_Python_Python 3.x_While Loop_Try Except - Fatal编程技术网

Python 清理try和except语句

Python 清理try和except语句,python,python-3.x,while-loop,try-except,Python,Python 3.x,While Loop,Try Except,您好,我正在制作一个代码,用户需要在其中输入一个介于0-255之间的数字,因此我希望使用try,但如果他们输入一个0-255之外的数字,则可以使用该代码输入字母和if语句。我写的没有错误,但它看起来很混乱,因为我必须调用输入两次等等。有什么想法可以清理一下/使它更简短、更容易阅读吗 try: user_input = int(input('Enter a number between 0 and 255 to be converted to 8-bit binary: '

您好,我正在制作一个代码,用户需要在其中输入一个介于0-255之间的数字,因此我希望使用try,但如果他们输入一个0-255之外的数字,则可以使用该代码输入字母和if语句。我写的没有错误,但它看起来很混乱,因为我必须调用输入两次等等。有什么想法可以清理一下/使它更简短、更容易阅读吗

    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.')
试试看:
user_input=int(输入('输入一个介于0和255之间的数字以转换为8位二进制:'))
如果用户输入>0且用户输入<255:
打破
其他:
user_input=int(输入('\n输入一个介于0和255之间的数字以转换为8位二进制:'))
除:
打印(“\n请输入一个有效的数字。”)

在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.')
为True时:
user_input=int(输入('输入一个介于0和255之间的数字以转换为8位二进制:'))
如果用户输入>0且用户输入<255:
打破
其他:
打印(“\n请输入一个有效的数字。”)