how to check if an input is valid before printing? [duplicate] - python

This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Check if numbers are in a certain range in python (with a loop)? [duplicate]
(3 answers)
Closed 4 years ago.
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?

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

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")

This is what I might do:
validResponse = False
while(not validResponse):
try:
num = int(input("Choose a number between 1 and 50: "))
if(1 <= num <= 50):
validResponse = True
else:
print("Invalid number.")
except ValueError:
print("Invalid number.")
This is, if you want to prompt them until a correct number has been entered. Otherwise, you can ditch the while loop and validResponse variable.
The try will run the statement until it runs into an error. if the error is specifically that the number couldn't be interpereted as an integer, then it raises a ValueError exception and the except statement tells the program what to do in that case. Any other form of error, in this case, still ends the program, as you'd want, since the only type of acceptable error here is the ValueError. However, you can have multiple except statements after the try statement to handle different errors.

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 and Ethan Thomas' answers).

Related

Fixing While Loops Python

We want to create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program reprompts the user for a valid number. Complete the following steps to write this code.
a.Write a line of code the prompts the user for number between 1 and 10.
number = float(input("Enter a number between 1 and 10: "))
b. Write a Boolean expression that tests the number the user entered by the code in step "a." to determine if it is not in range.
x = (number > 10 or number < 1)
c.Use the Boolean expression created in step b to write a while loopthat executes when the user input is out of range. The body of the loop should tell the user that they enteredan invalid number and prompt them for a valid number again.
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
d.Write the code that prints a message telling the user that they entered a valid number.
if x == False:
print("wow, you printed a number between 1 and 10!")
I answered the stuff for the question, but my problem is that whenever the user enters a wrong number on their first try and a correct number on their second try, the program still considers it as an invalid input. How do I fix this???
Rewrite this line in the while loop:
x = (number > 10 or number < 1)
so it becomes
while x == True:
print("you printed an invalid number")
number = float(input("please enter the number again, this time between 1 and 10"))
x = (number > 10 or number < 1)
This changes the value of x so it doesn't stay at True
If you use a while True construct, you won't need to repeat any code. Something like this:
LO, HI = 1, 10
while True:
input_ = input(f'Enter a number between {LO} and {HI}: ')
try:
x = float(input_)
if LO <= x <= HI:
print(f'Wow! You entered a number between {LO} and {HI}')
break
print(f'{input_} is not in range. Try again')
except ValueError:
print(f'{input_} is not a valid number. Try again')
Note:
When asking for numeric input from the user, don't assume that their input can always be converted properly. Always check
The following code snippet should do all you need:
number = float(input("Please input a number: "))
while (number > 10 or number < 0):
number = float(input("Error. Please input a new number: "))
Use an infinite loop, so that you can prompt for the input only once.
Use break to terminate the loop after the number in the correct range is entered.
Use f-strings or formatted string literals to print the message.
while True:
num = float(input('Enter a number between 1 and 10: '))
if 1 <= num <= 10:
print('Wow, you printed a number between 1 and 10!')
break
else:
print(f'You printed an invalid number: {num}!')

Limiting an input between Two Numbers and checking if the input is a number or not at the same time

I have been trying to improve my guessing game in Python by limiting the guess input
between 2 numbers(1 and 100) and asking if the guess input is a number or not. I have been trying to do this both at the same time. Is there anyway I can do this by minimum coding?
You can use a while loop to keep asking the user for a valid input until the user enters one:
while True:
try:
assert 1 <= int(input("Enter a number between 1 and 100: ")) <= 100:
break
except ValueError, AssertionError:
print("Input must be an integer between 1 and 100.")
while True:
try:
number = raw_input("Enter a number between 1 and 100: ")
if number.isdigit():
number=int(number)
else:
raise ValueError()
if 1 <= number <= 100:
break
raise ValueError()
except ValueError:
print("Input must be an integer between 1 and 100.")
it is a small improvement over the answer by #blhsing , so that the program does not crash on string input

Python: random number game with input validation

I'm writing a program that is a guessing game where the user has one chance to guess a number between 1 and 20.
There are two problems with the code:
Number one is still the input validation. The firstGuess variable is actually in main().
firstGuess = userguess()
def userGuess():
while True:
try:
guess = int(input('Enter a number between 1 and 20: '))
if 1 <= guess >= 20:
return guess
except ValueError:
print (guess, 'is not a valid guess!')
break
What I'm trying to do is put the input validation in a loop (while True:) until the user gives good input (in this case a positive number between 1 and 20). If the user were to enter 'd', or '-5', the program should continue looping until good input is given. However, this is not the case. By adjusting the code, I have been able to ask for the input again once bad input is entered, but if bad input is given a third time I get "another exception occured while handling this exception."
*Removed other problem, #Henry Woody was correct in that I wasn't using the conditionals correctly.
The issues are with the conditionals.
The first is the line:
if 1 <= guess >= 20:
in userGuess, which is checking for a number greater than or equal to 20, which is not what you want. You can fix this issue by changing the condition to:
if 1 <= guess <= 20:
Next, the conditional:
if guess1 == randomOne or randomTwo or randomThree:
checks whether guess1 == randomOne or if randomTwo is truthy or if randomThree is truthy. It does not check if guess1 == randomOne or guess1 == randomTwo or guess1 == randomThree as intended. You can fix this by changing the condition to:
if guess1 in [randomOne, randomTwo, randomThree]:
to check if guess1 is equal to either of the three random variables.
Edit:
There is also an issue in the try/except block. If the user enters a non-digit character in the input, a ValueError will be raised before guess is defined. But then guess is referenced in the except block, but guess isn't defined at that point.
You can fix this by getting the user input and then, separately, trying to convert the input to an int.
Here's an example:
while True:
guess = input('Enter a number between 1 and 20: ')
try:
guess = int(guess)
if 1 <= guess <= 20:
return guess
except ValueError:
print (guess, 'is not a valid guess!')
break

Python: Input validation against a float and a string

This code takes the users input and changes it to an integer and then checks if the int is between 0 and 10. I would also like this code to validate the users input against floats and non-numerical strings and loop back if the user enters a bad input. EX: user inputs 3.5 or "ten" and gets an Error and loops again.
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
while pyramid < 0 or pyramid > 10:
print("That value is not in the correct range. Please try again.")
pyramid = int(input("Please enter an integer between 0 and 10 to begin the sequence: "))
I'd suggest to try to:
loop indefinitely (while 1)
Cast the input to a float, if this succeeds you can check if it has any decimals (pyramid % 1 != 0) and print the appropriate error in this case.
Cast the input to a integer and break the loop, if it is.
print an error that the input is not an integer
while 1:
str_in = input("Please enter an integer between 0 and 10 to begin the sequence: ")
try:
pyramid = float(str_in)
if(pyramid % 1 != 0):
print("That value is a float not an integer. Please try again.")
continue
except:
pass
try:
pyramid = int(str_in)
if pyramid >= 0 and pyramid <= 10:
break
except:
pass
print("That value is a string not an integer. Please try again.")
print("Your value is {}".format(pyramid))

User restrictions integer

How to narrow input of a integer to a certain length like "7" (per example) from a user raw_input:
def number():
number=int(input("Number:"))
print(number)
number=1234567
It has to have an while condition where it says if len(number) < 7 or len(number) > 7:
print("Error")
phone=int(input("Number:"))`
Thank you & Merry Xmas
check the length before you try casting to int:
def number():
while True:
i = input("Number:")
if len(i) > 7:
print("Number can only contain at most 7 digits!")
continue
try:
return int(i)
except ValueError:
print("Invalid input")
If you want exactly 7 use if len(i) != 7 and adjust the error message accordingly. I also used a try/except as because the length is seven does not mean it is a valid string of digits. If you want to allow the minus son you could if len(i.lstrip("-")) > 7:

Categories