0

I was requested to create an legal age verification program using a user's year of birth. I have managed to limit the users integer input to 4 digits but it does allow the user to enter any number within a four digit range (0, 234, 1234 etc). How to I force a 4 digit input and forbid 'inputs' below 1940?

I have tried a WHILE statement, IF statement, a len() function but none of them work.

# Welcome user to the program
greeting = "Hello! Welcome to the age calculator."
print(greeting)

print("\n")

# Input current year
current_year = 2019
# Request the users year of birth and provide eg of birth year to guide user input to 4 digits
# Set integer digit limit to max 4 
birth_year = int(input("Please confirm the year of your birth " + "\n" + "eg:'1989'" + "\n")[:4])
# Use basic sum to calculate users age using this year 
age = current_year - birth_year
print(age)

# use IF statement to add legal age
if age >= 18:

print("Congrats you are old enough")

Expected outcome is a valid year of birth between 1940 and the current year.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    You have shown none of those attempts, nor what *"none of them work"* actually means, so it's impossible to say what you were doing wrong. Give a [mcve]. – jonrsharpe Jul 27 '19 at 15:26
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – jonrsharpe Jul 27 '19 at 15:27

2 Answers2

0

As stated in the comments, the question was not very clear. But I assume you want to keep requesting the user for his birth year if he inputs something smaller than 1940? If more conditions are needed, please improve your question.

If that's the case, then this should suffice:

birth_year = 0
while birth_year < 1940:

    birth_year = int(input("Please confirm the year of your birth " + "\n" + "eg:'1989'" + "\n")[:4])

    age = current_year - birth_year
    print(f'Your age: {age}')

    if age >= 18:

        print("Congrats you are old enough")

If you wish for very strict rules for the input, you might want to use Regular Expressions, which can be implemented through the use of the regex Python library.

Philippe Fanaro
  • 6,148
  • 6
  • 38
  • 76
0

You may also want to prevent people entering years after the current year. This checks for both upper and lower limits. (Would also use

# Request the users year of birth and provide eg of birth year to guide user input to 4 digits
# Set integer digit limit to max 4 
birth_year = int(input("Please confirm the year of your birth " + "\n" + "eg:'1989'" + "\n")[:4])
while ((birth_year <= 1940) or (birth_year >= current_year)):
    print("Please try again")
    birth_year = int(input("Please confirm the year of your birth " + "\n" + "eg:'1989'" + "\n")[:4])

# Use basic sum to calculate users age using this year 
Zak M.
  • 186
  • 6