Home > Blockchain >  How to create a exception for a while loop to repeat a input
How to create a exception for a while loop to repeat a input

Time:10-01

I am trying to get this bit of code to work to validate the following input. I want to only accept inputs 1,2,or 3. Here is what I have so far:

number = int(input('Enter a number:'))
done = False
while not done:
    try:
        if number < 3:
            done = True
    except:
        number = input("Please enter a valid number:")

The expected out put that I want if the input to loop until I get either 1,2, or 3. Right now it won't do anything to when I input something greater than three. I want to use this number as an input to another function. Any help would be great of if you need more information please let me know!

CodePudding user response:

Try this

number = int(input('Enter a number:'))
done = False
while not done:
    if number <= 3:
        done = True
    else:
        number = int(input("Please enter a valid number:"))

except block only run when there is an error in try block code.

Use if-else statement.

You can use this one too.

number = int(input('Enter a number:'))
done = False
while number>3:
    number = int(input('Please enter a valid number:'))

CodePudding user response:

Walrus operator (:=) comes in handy to validate input while its value greater than 3 or lesser/equals than 0 and only accept 1, 2, or 3.

while not 3 >= (number := int(input('Enter a number:'))) > 0:
    print('Please enter a valid number')

or:

while (number := int(input('Enter a number:'))) not in (1,2,3):
    print('Please enter a valid number')

Output:

# Enter a number:0
# Please enter a valid number
# Enter a number:-1
# Please enter a valid number
# Enter a number:4
# Please enter a valid number
# Enter a number:3

Process finished with exit code 0
  • Related