[Tutor] if-else statements

Andre Engels andreengels at gmail.com
Fri Oct 14 09:42:43 CEST 2005


2005/10/14, andrade1 at umbc.edu <andrade1 at umbc.edu>:
> Hello
>
> I'm having some trouble with my if, else statements. For some reason, the
> months that have 31 days work fine, but the months that have 28/30 do not
> work. Am I doing something wrong? it is supposed to take a date as an
> input like 9/31/1991 and then say that the date is not valid because
> september only has 30 days.

First hint:
Where is 'month' used in your program? The answer is: nowhere. It
should be used. Why?

Second hint:
Currently, the program checks each date first for validity with
respect to January, then throws the outcome away to do the same with
February, etcetera upto December. Thus, the final outcome says whether
the date is correct in December, not whether it is correct in the
given month.

(actual code below)

> import string
>
> def main():
>     # get the day month and year
>     month, day, year = input("Please enter the mm, dd, yyyy: ")
>     date1 = "%d/%d/%d" % (month,day,year)
>
>     months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
>
>     if day <= months[1]:
>         d = "valid"
>     else:
>         n = "not valid"
>
>     if day <= months[2]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[3]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[4]:
>         d = "valid"
>     else:
>         n = "not valid"
>
>     if day <= months[5]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[6]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[7]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[8]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[9]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[10]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[11]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     if day <= months[12]:
>         d = "valid"
>     else:
>         d = "not valid"
>
>     print "The date you entered", date1, "is", d +"."
>
> main()

Correct and shortened code:

Instead of the whole line "if day <= months[1]"... series of
if-then-else statements, use only one statement, namely:

if day <= months[month]:
    d = "valid"
else:
    d = "not valid"

--
Andre Engels, andreengels at gmail.com
ICQ: 6260644  --  Skype: a_engels


More information about the Tutor mailing list