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')
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
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
num = int(input('Choose a number between 1 and 50'))
You could also implement error handling (as seen in Moonsik Park's answer).