7
\$\begingroup\$

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.')
\$\endgroup\$
  • 1
    \$\begingroup\$ This will return the wrong answer if your birthday is later in the year. Case in point. If someone was born in December of 1998, that person is currently 17 but this code would say 18. \$\endgroup\$ – mdfst13 Jul 22 '16 at 9:53
  • 1
    \$\begingroup\$ @BusyAnt hi i also discovered this strange scenario. Enter Year Of Birth: -100>>> This is not a number, try again. Enter Year Of Birth: -100 You are 2116 years old. Welcome To The Portal. >>> >>> ================================ RESTART ================================ >>> Enter Year Of Birth: +100 You are 1916 years old. Welcome To The Portal. >>> \$\endgroup\$ – Megadon.cyber Jul 22 '16 at 15:08
  • \$\begingroup\$ +100 and -100 work perfectly on my computer... And the age it gives is right : if you are born in year 100, you are 2116 years old ; if you are born in year -100, you are 1916 years old \$\endgroup\$ – BusyAnt Jul 22 '16 at 17:39
3
\$\begingroup\$

I think what I would change it were the picking current year process, so it becomes dynamic and not hard coded, and maybe reduce the info about my age in one line:

from datetime import date
current_year = date.today().year
year_of_birth = int(raw_input('Enter Year Of Birth: '))
age = current_year - year_of_birth
print('You are %s years old.' % age)
if age < 18:
    print('YOU SHALL NOT PASS!')
else:
    print('Welcome To The Portal.')
\$\endgroup\$
  • \$\begingroup\$ Just saw my higher-voted answer getting un-accepted and this one instead after 3 years of inactivity... Why? The only information in this answer is already contained in the other one, it is litterally the first line of a more complete analysis. \$\endgroup\$ – BusyAnt Nov 11 at 8:24
  • \$\begingroup\$ Askers' prerogative, I'm afraid. Have an upvote for your admittedly better answer. \$\endgroup\$ – Gloweye Nov 11 at 11:56
  • \$\begingroup\$ Thanks. You're right; in the end, it's the asker's choice which answer should be accepted. \$\endgroup\$ – BusyAnt Nov 11 at 12:11
8
\$\begingroup\$

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)
\$\endgroup\$
  • \$\begingroup\$ You're welcome. Don't hesitate if there remains unclear parts in my answer :) \$\endgroup\$ – BusyAnt Jul 22 '16 at 14:19
  • \$\begingroup\$ i found this when negative and positives are used with an integer. seems to add current year to suggested + or - integer. What do you think \$\endgroup\$ – Megadon.cyber Jul 22 '16 at 15:04
  • \$\begingroup\$ I'm not sure what you're asking about... Are you talking about the user input ? If the user enters a negative integer, substracting current year and this number will be like adding the current year and the positive opposite of the user number \$\endgroup\$ – BusyAnt Jul 22 '16 at 15:09
  • \$\begingroup\$ I need to restrict it from processing negative number input.. \$\endgroup\$ – Megadon.cyber Jul 22 '16 at 19:10
  • 1
    \$\begingroup\$ See updated answer :) \$\endgroup\$ – BusyAnt Jul 22 '16 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.