Loop on if-statement to reject invalid input [duplicate] - python

This question already has answers here:
Integers as the only valid inputs
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
In python is there a way to redo a raw input and if statement if the answer is invalid?
So for instance if you ask the user to guess 1 or 2, and they guess 3 you create the additional elif or else to tell the user that the answer is invalid and go through the raw input / if statement again?

I believe you want something like this:
# Loop until a break statement is encountered
while True:
# Start an error-handling block
try:
# Get the user input and make it an integer
inp = int(raw_input("Enter 1 or 2: "))
# If a ValueError is raised, it means that the input was not a number
except ValueError:
# So, jump to the top of the loop and start-over
continue
# If we get here, then the input was a number. So, see if it equals 1 or 2
if inp in (1, 2):
# If so, break the loop because we got valid input
break
See a demonstration below:
>>> while True:
... try:
... inp = int(raw_input("Enter 1 or 2: "))
... except ValueError:
... continue
... if inp in (1, 2):
... break
...
Enter 1 or 2: 3
Enter 1 or 2: a
Enter 1 or 2: 1
>>>

Use a while statement:
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
while x != 1 and x != 2:
print 'Invalid!'
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
This code starts off by taking the necessary input. Then, using a while loop, we check to see if x is 1 or 2. If not, we enter the while loop and ask for input again.
You could also do this:
while True:
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
if x in [1, 2]:
break

Related

'Perfect factorial' python program [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.

Collatz - Automate the Boring Stuff with Python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am completely new to python and I just completed the first python project in the book. However, I am trying to improve my code so that the program will continue running until the user enters a valid integer. Currently if a user provides an input that's not an integer, the program just says 'Please enter an integer' and exits. How do I achieve this? I have been trying for hours but is still unable to get to a conclusion.
#! python3
def collatz(number):
if (number % 2) == 0:
result = number // 2
print(result)
return(result)
else:
result = (3 * number) + 1
print(result)
return(result)
try:
givenNumber = int(input('Enter a number: '))
while givenNumber != 1:
givenNumber = collatz(givenNumber)
except ValueError:
print('Please enter an integer.')
You can wrap your logic inside a while loop:
while True:
try:
givenNumber = int(input('Enter a number: '))
# break here if condition True
except ValueError:
print('Please enter an integer.')
I'm not sure it related to python programming specific, but try to learn from the exampls as this one:
def collatz(number):
if (number % 2) == 0:
result = number // 2
print(result)
return(result)
else:
result = (3 * number) + 1
print(result)
return(result)
givenNumber = None
while not isinstance(givenNumber,int):
givenNumber = input('Enter a number: ')
try:
givenNumber = int(givenNumber)
except ValueError:
print("this is not an integer number")
givenNumber = collatz(givenNumber)
output for example:
Enter a number: 3.2
this is not an integer number
Enter a number: 2
1

"Try and Except" to differentiate between strings and integers? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I'm a beginner in the Python language. Is there a "try and except" function in python to check if the input is a LETTER or multiple LETTERS. If it isn't, ask for an input again? (I made one in which you have to enter an integer number)
def validation(i):
try:
result = int(i)
return(result)
except ValueError:
print("Please enter a number")
def start():
x = input("Enter Number: ")
z = validation(x)
if z != None:
#Rest of function code
print("Success")
else:
start()
start()
When the above code is executed, and an integer number is entered, you get this:
Enter Number: 1
Success
If and invalid value however, such as a letter or floating point number is entered, you get this:
Enter Number: Hello
Please enter a number
Enter Number: 4.6
Please enter a number
Enter Number:
As you can see it will keep looping until a valid NUMBER value is entered. So is it possible to use the "try and except" function to keep looping until a letter is entered? To make it clearer, I'll explain in vague structured English, not pseudo code, but just to help make it clearer:
print ("Hello this will calculate your lucky number")
# Note this isn't the whole program, its just the validation section.
input (lucky number)
# English on what I want the code to do:
x = input (luckynumber)
So what I want is that if the variable "x" IS NOT a letter, or multiple letters, it should repeat this input (x) until the user enters a valid letter or multiple letters. In other words, if a letter(s) isn't entered, the program will not continue until the input is a letter(s). I hope this makes it clearer.
You can just call the same function again, in the try/except clause - to do that, you'll have to adjust your logic a bit:
def validate_integer():
x = input('Please enter a number: ')
try:
int(x)
except ValueError:
print('Sorry, {} is not a valid number'.format(x))
return validate_integer()
return x
def start():
x = validate_integer()
if x:
print('Success!')
Don't use recursion in Python when simple iteration will do.
def validate(i):
try:
result = int(i)
return result
except ValueError:
pass
def start():
z = None
while z is None:
x = input("Please enter a number: ")
z = validate(x)
print("Success")
start()

Checking that input is an integer between 1 and 3 - Python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I want to be able to check that an input is an integer between 1 and 3, so far I have the following code:
userChoice = 0
while userChoice < 1 or userChoice > 3:
userChoice = int(input("Please choose a number between 1 and 3 > "))
This makes the user re-enter a number if it is not between 1 and 3, but I want to add validation to ensure that a user cannot enter a string or unusual character that may result in a value error.
Catch the ValueError:
Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value
Example:
while userChoice < 1 or userChoice > 3:
try:
userChoice = int(input("Please choose a number between 1 and 3 > "))
except ValueError:
print('We expect you to enter a valid integer')
Actually, since the range of allowed numbers is small, you can operate directly on strings:
while True:
num = input('Please choose a number between 1 and 3 > ')
if num not in {'1', '2', '3'}:
print('We expect you to enter a valid integer')
else:
num = int(num)
break
Alternatively try comparison of input in desired results, and break from the loop, something like this:
while True:
# python 3 use input
userChoice = raw_input("Please choose a number between 1 and 3 > ")
if userChoice in ('1', '2', '3'):
break
userChoice = int(userChoice)
print userChoice
Using Try/Except is a good approach, however your original design has a flaw, because user can still input like "1.8" which isn't exactly an integer but will pass your check.

Check if input is positive integer [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.

Categories