【问题标题】:Cleaning up try and except statement [duplicate]清理try和except语句[重复]
【发布时间】:2020-06-08 13:56:33
【问题描述】:

您好,我正在制作一个代码,用户需要在其中输入一个 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.')

【问题讨论】:

    标签: python python-3.x while-loop try-except


    【解决方案1】:

    在 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.')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2017-11-30
      • 2018-03-13
      • 2013-04-10
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多