Reputation:
In python, I need the input of a user to be between a range of years.
Using if statement returns the error (if he's out of range) to the user and invite him to make another choice of year.
The second time he chooses a year need to be tested again with the same conditions. Which doesn't happen yet.
What would be the best solution to have his input tested all over again, until conditions are met ?
Here's some piece of the actual code
year = input("Enter a year between 1900 and 2099 : ")
if year >= "1900" or year <= "2099":
year = (input("The year you entered is out of range, please try again : "))
year = int(year)
Thanks in advance
Upvotes: 1
Views: 57
Reputation: 2441
You can use a while
loop. A while
loop will run until a certain condition is False
. In this case it will run until the break
keyword is used, because the condition will always be True
. You can also use try
and except
do make sure the input it an integer. And use continue
to start the loop again if it is not an integer.
prompt = "Enter a year between 1900 and 2099: "
while True:
year = input(prompt)
try:
year = int(year)
except ValueError:
prompt = "The year you entered is out of range, please try again : "
continue
if year >= 1900 or year <= 2099:
break
else:
prompt = "The year you entered is out of range, please try again : "
Upvotes: 1