0

Hi I'm making a code and in it a user needs to enter a number between 0-255 and so I wish to use a try except incase they, for example enter a letter and an if statement with that if they enter a number outside 0-255. I've written it with no errors but it seem very messy as I have to call the input twice etc. any ideas how to clean this up/make it a bit shorter and easier to read.

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

1 Answers1

0

In python, try/except is about handling exceptions. In your code, I don't see any exceptions being raised. How about using a while loop to ensure the user inputs a valid number? Something like:

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.')
jpapadakis
  • 58
  • 7