[Tutor] Need help with dates in Python
Steven D'Aprano
steve at pearwood.info
Wed Mar 9 21:02:30 CET 2011
nookasree ponamala wrote:
> Hi,
> I'm new to Python programming. I've changed the code to below, but still it is not working, Could you pls. make the corrections in my code.
If you are to be a programmer, you need to learn how to read the error
messages you get. You probably would have seen an error something like this:
>>> if True:
... pass
File "<stdin>", line 2
pass
^
IndentationError: expected an indented block
or like this:
>>> while True:
... pass
... if True:
File "<stdin>", line 3
if True:
^
IndentationError: unexpected indent
This will tell you *exactly* what is wrong: you haven't indented the if
block (see below), or possibly indented the wrong part. I'm not sure
which, because you seem to have mixed spaces and tabs, or possibly my
mail client Thunderbird is messing about with the indentation.
In general, never ever mix spaces and tabs for indentation! Even when
Python allows it, it becomes hard to maintain and harder to email it.
If this is not your error, then please COPY and PASTE the FULL error you
receive, do not retype it or summarize it in any way.
> import datetime
> t = ()
> tot = []
> min = datetime.date(2008, 1, 1)
> max = datetime.date(2012, 12, 31)
> for line in open ('test2.txt','r'):
> data = line.rstrip().split()
> a = data[9]
> b = data[4]
> (year, month, day) = b.split('-')
> year = int(year)
> month = int(month)
> day = int(day)
> t = (year,month,day)
> if t < max:
This is wrong. The if statement should be indented equally to the line
above it. Only the if *block* should be indented further:
if condition: # do not indent
# indent this block
do_something()
elif another_condition: # outdent
# indent this block
do_something_else()
and_more()
even_more()
else: # outdent
# and indent the block again
do_something_else()
> maxyr = max
> if t > min:
> minyr = min
And again here: at *least* one line must be indented after the if statement.
> t = (a,b,maxyr,minyr)
> tot.append(t)
> print t
--
Steven
More information about the Tutor
mailing list