HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Age verification module in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
moduleagepythonverification

Problem

I wrote an age verification module in Python 2.5 . How can I improve on current_year? import time perhaps?

current_year = 2016
year_of_birth = int(raw_input('Enter Year Of Birth: '))
age = current_year - year_of_birth
mytext = 'You are %s years old.'
print(mytext % age)
if age < 18:
    print('YOU SHALL NOT PASS!')
else:
    print('Welcome To The Portal.')

Solution

Current year

If you don't want the current year to be hardcoded, you could use the method today() from datetime.date.

from datetime import date
current_year = date.today().year


User input

You should always put your user input request in a try/except block, because you never knows what the user will think and do. I'd go with:

def ask_for_birth_year():
    while True:
        try:
            return int(raw_input('Enter Year Of Birth: '))
        except ValueError:
            print('This is not a number, try again.')


This way it will keep asking until the user enters a proper number.

UPDATE (following comment) :

If you need some restriction on the input number, you could try this kind of structure :

def ask_for_birth_year():
    while True:
        try:
            nb = int(raw_input('Enter Year Of Birth: '))
            if nb < 0:  # can be any condition you want, to say 'nb' is invalid
                print('Invalid year')
            else:  # if we arrive here, 'nb' is a positive number, we can stop asking
                break
        except ValueError:
            print('This is not a number, try again.')
    return nb


Other remarks

Since age is an integer, you'll prefer using %d instead of %s (strings) in your print call.

mytext = 'You are %d years old.'


It is also recommended that you put all level-0 code under a __name__ == '__main__' condition, to avoid having it launched later when you import this module. This is a good habit to take, you can read about it in the brand new StackOverflow Documentation here.

if __name__ == '__main__':
    # do stuff


Finally, the limit age (18), is what we call a magic number. It should be avoided, if you plan on making your code grow, and replaced by a meaningful constant.

#at the beginning
LIMIT_AGE = 18

#your 'if' statement
if age < LIMIT_AGE:
    ...


Altogether

from datetime import date

LIMIT_AGE = 18    

def ask_for_birth_year():
    while True:
        try:
            nb = int(raw_input('Enter Year Of Birth: '))
            if nb < 0:
                print('Invalid year')
            else:
                break
        except ValueError:
            print('This is not a number, try again.')
    return nb

def print_message(age):
    mytext = 'You are %d years old.'
    print(mytext % age)
    if age < LIMIT_AGE:
        print('YOU SHALL NOT PASS!')
    else:
        print('Welcome To The Portal.')

if __name__ == '__main__':
    year_of_birth = ask_for_birth_year()
    current_year = date.today().year
    age = current_year - year_of_birth
    print_message(age)

Code Snippets

from datetime import date
current_year = date.today().year
def ask_for_birth_year():
    while True:
        try:
            return int(raw_input('Enter Year Of Birth: '))
        except ValueError:
            print('This is not a number, try again.')
def ask_for_birth_year():
    while True:
        try:
            nb = int(raw_input('Enter Year Of Birth: '))
            if nb < 0:  # can be any condition you want, to say 'nb' is invalid
                print('Invalid year')
            else:  # if we arrive here, 'nb' is a positive number, we can stop asking
                break
        except ValueError:
            print('This is not a number, try again.')
    return nb
mytext = 'You are %d years old.'
if __name__ == '__main__':
    # do stuff

Context

StackExchange Code Review Q#135570, answer score: 9

Revisions (0)

No revisions yet.