1

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

1
  • Are you sure you want conditions like year >= "1900"? This will do a string lexicographical comparison, as opposed to comparing if the year is less than 1900. For example, 'a' >= '1900' evaluates to True because a has a larger ASCII value than 1. Also, '19000' >= '1900' or '19000' <= '2099' will also evaluate to True. Commented Jan 20, 2021 at 2:16

1 Answer 1

1

Explanation:

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.

Code:

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 : "
Sign up to request clarification or add additional context in comments.

9 Comments

should year = int(year) be exactly below the year assignment?
@zois Thanks for pointing it out, I'll fix that.
Actually you are checking for strings with the if statement, so it works as it is
@zois I'll probably make it integers.
Great, thanks for your input. Strings removed as well. My mistake, or habit.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.