# how to check if an input is valid before printing?

912 views
3

Let's say I want the user to input a number between 1 and 50, so I do:

``````num = input("Choose a number between 1 and 50: ")
``````

But if the user inputs a number that does not fall between 1 and 50, i want it to print:

Choose a number between 1 and 50: invalid number

How can I do that?

What have you tried? What specifically do you need help with?

I tried to put an if statement before the input but that didn't work it out, then I tried to make something like a list compreension with an if statement and that gives me invalid syntax

@AugustoD'Arruda: Did you try something like petruz's answer below?

The user needs to input a number so that you can check if that number falls between 1 and 50. Without inputting a number, you can not know whether it is a valid number or not.

@Bazingaa I'm trying it right now. I was trying to do something and I couldn't work it out.

11

``````num = input("Choose a number between 1 and 50: ")

try:
num = int(num) #Check if user input can be translated to integer. Otherwise this line will raise ValueError
if not 1 <= num <= 50:
print('Choose a number between 1 and 50: invalid number')
except ValueError:
print('Choose a number between 1 and 50: invalid number')
``````

posted this
3

You need the input to be set to an integer since otherwise it would be a string:

``````num = int(input("Choose a number between 1 and 50: "))
``````

Check what num has been set to:

``````if 1 < num < 50:
print(1)
else:
print("invalid number")
``````

posted this
11

In addition to the above answers, you can also use an assertion. You're likely going to use these more so when you're debugging and testing. If it fails, it's going to throw an `AssertionError`.

``````num = input('Choose a number between 1 and 50') # try entering something that isn't an int

assert type(num) == int
assert num >= 1
assert num <= 50

print(num)
``````

You can use an `if` statement, but you need to assign the input to a variable first then include that variable in the conditional. Otherwise, you don't have anything to evaluate.

``````num = input('Choose a number between 1 and 50')

if type(num) == int: # if the input isn't an int, it won't print
if num >= 1 and num <= 50:
print(num)
``````

By default, the input provided is going to be a string. You can call the built-in function `int()` on the input and cast it to type `int`. It will throw a `ValueError` if the user enters something that isn't type `int`.

``````num = int(input('Choose a number between 1 and 50'))
``````

You could also implement error handling (as seen in Moonsik Park's answer).

posted this