[Tutor] If, elif, else

Alan Gauld alan.gauld at btinternet.com
Wed Jan 29 02:47:59 CET 2014


On 28/01/14 22:46, Michael L. Pierre wrote:
> I am a newbie with Python (programming in general)

Welcome to the list.

> I have gotten it resolved to the point that it understands leap  years
> and gives the correct age.

OK, I'll believe you, at least for now... :-)

>  My problem arises when a date is input that
> is the current month, but a future date (i.e. today’s date is 1/28/2014
> but the input dob is 1/30/1967)

I don;t understand that. How is 1967 a future date?
Do you just mean the fact that the day is bigger than todays day?

> It skips over the elif option to
> subtract one year and prints out ***HAPPY BIRTHDAY***

Unfortunately  its hard to tell exactly whats going on
because we can't see where much of the data comes from.
I'll make a few comments below but I'm not sure if they will help 
pinpoint your main issue.

> if leap_year != int:

No idea what this is supposed to be doing?
It is comparing leap_year to a type object.
I doubt very much if this 'if' test ever fails.

>      age_month = int(current_split[1]) - int(dob_split[1])

No idea what current_split or dob_split are. Since you are
converting them to int I'll assume string lists maybe?

>      if age_month != 0:
>          month_less = 1
>          age = int(current_split[0]) - int(dob_split[0]) - month_less
>          print "you are", age, "years old"
>
>      elif age_month == 0 and int(current_split[2]) > int(dob_split[2]):
>          age = int(current_split[0]) - int(dob_split[0]) - month_less

Note that you use month_less here even though you don't assign it a 
value as you did in the if block.
Does it already have a value or is that an oversight?

>          print "you are", age, "years old"

>      else:
>         age = int(current_split[0]) - int(dob_split[0])
>         print "You are", age, "and today is your birthday ***HAPPY
> BIRTHDAY***"

I assume you haven't found the datetime module yet?
It will take much of the hassle of date/time calculations away.
Or maybe you are doing it the hard way as a learning exercise?
That's OK too. :-)

A final thought. It might be worth putting some debug print
statements in so you can see what the values in the tsts are.

eg just before the if block put

print 'age_month = ', age_month

Also instead of relying on arithmetic you could maybe create some 
intermediate values.
Instead of
int(current_split[0]) - int(dob_split[0])

being calculated twice store it as a value, maybe called 
month_difference or similar?

It all helps make the code clearer and therefore easier
to debug.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list