I want to force the users input to be between two numbers e.g. 5-15 and if it isn't between or equal too these numbers say please enter a number between these two and request another input.
I already have an input that forces you to enter an interger.
while True:
try:
# asking for race length
race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15)"))
except ValueError:
print("Sorry, I didn't understand that.")
#if an interger isn't entered do loop above to avoid and error
continue
else:
#race length succesfully found
#finished the loop
break
Use if-else to check if the value is within the required range or not if yes then assign it to the race_length
if not ask user to enter again.
if(x>5 and x<15):
race_length = x
else:
input('Choose the Length You Would Like You Race To Be (Between 5 and 15)')
You can do it raise an error using assert <bool> and handle AssertionError
See the following code,
while True:
try:
race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15) : "))
assert 5 < race_length < 15
except ValueError:
print("Sorry, I didn't understand that.")
except AssertionError:
print("Please Enter a number between 5 and 15")
else:
break
Related
while True:
try:
name=str(input("Enter your name="))
age=int(input("Enter your age="))
except ValueError:
print("error!! please enter the values again")
continue
else:
break
current_year=int(input("What is the current year you are living in="))
n=100-age
x=n+current_year
print(name,"",x,"is the year you will turn 100")
So how do I create an error msg for my use if he/she enter a negative number for the age, such that it allows the user to re-input the age.
Add a while loop which asks if the age is smaller than zero. If this condition is satisfied (the user entered a negative digit), the loop will go on (it will ask for a new input):
while True:
try:
name=input("Enter your name=")
age=int(input("Enter your age="))
while age < 0:
age=int(input("Enter your age="))
current_year=int(input("What is the current year you are living in="))
except ValueError:
print("error!! please enter the values again")
continue
else:
break
n=100-age
x=n+current_year
print(name,"",x,"is the year you will turn 100")
I would try something using a while loop.
while age < 0:
age=int(input("Enter your age="))
if age < 0:
print('try again')
We keep on taking user's age until they enter something above 0.
We are learning exception handling. Did I do this correctly? Is ValueError the correct exception to use to catch strings being typed instead of numbers? I tried to use TypeError, but it doesn't catch the exception.
Also, is there a more efficient way to catch each exception in my four inputs? What is best practice here?
#Ask user for ranges. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
rangeLower = float(input("Enter your Lower range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
rangeHigher = float(input("Enter your Higher range: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
#Ask user for numbers. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
try:
num1 = float(input("Enter your First number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
while True:
try:
num2 = float(input("Enter your Second number: "))
except ValueError:
print("You must enter a number!")
else:
#Break the while-loop
break
Here you are experiencing what is called, WET code Write Everything Twice, we try to write DRY code, i.e. Don't Repeat Yourself.
In your case what you should do is create a function called float_input as using your try except block and calling that for each variable assignment.
def float_input(msg):
while True:
try:
return float(input(msg))
except ValueError:
pass
range_lower = float_input('Enter your lower range: ')
...
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
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
Beginner here, looking for info on input validation.
I want the user to input two values, one has to be an integer greater than zero, the next an integer between 1-10. I've seen a lot of input validation functions that seem over complicated for these two simple cases, can anyone help?
For the first number (integer greater than 0, I have):
while True:
try:
number1 = int(input('Number1: '))
except ValueError:
print("Not an integer! Please enter an integer.")
continue
else:
break
This also doesn't check if it's positive, which I would like it to do. And I haven't got anything for the second one yet. Any help appreciated!
You could add in a simple if statement and raise an Error if the number isn't within the range you're expecting
while True:
try:
number1 = int(input('Number1: '))
if number1 < 1 or number1 > 10:
raise ValueError #this will send it to the print message and back to the input option
break
except ValueError:
print("Invalid integer. The number must be in the range of 1-10.")
Use assert:
while True:
try:
number1 = int(input('Number1: '))
assert 0 < number1 < 10
except ValueError:
print("Not an integer! Please enter an integer.")
except AssertionError:
print("Please enter an integer between 1 and 10")
else:
break
class CustomError(Exception):
pass
while True:
try:
number1 = int(raw_input('Number1: '))
if number1 not in range(0,9):
raise CustomError
break
except ValueError:
print("Numbers only!")
except CustomError:
print("Enter a number between 1-10!)
how can i limit the input for srj imbetween 1 and 0 and it just restarts the whole program
def gen0(): # input all the initial data
while True: # this will loop infinitely if needed
try: # this will try to take a float from the user
j=int(input('how many juveniles are there in generation 0? '))
srj=float(input('what is the survival rate of juveniles '))
break # if the user gives a number then break the loop
except ValueError: #if the user does not give a number then the user will be told to retry
print("Sorry, there was an error. Please enter a positive number")
Since you are breaking within a try/except, you can simple raise a ValueError if the data is incorrect.
if srj > 1.0 or srj < 0.0:
raise ValueError
put the if statement if srj > 1 or srj < 0:gen0() before the break line
:^)