# Potus: Date/Time lesson

Nitty gritty question here…

I’m in lesson 10 of “Working with Dates and Times in Python”

Playing around shows me that the following two answers result in different values for the appt_lengths dictionary. In my brain, these two approaches are equivalent but clearly, they are not.

The key difference is in the phrasing of the if/then statement. Using an else clause has one lower value than the if in approach. I’m going to assume I’m misusing frequency tables somewhere, but I’m not seeing how clearly. Can anyone help me see this? Thanks!

using else:

``````for row in potus:
appt_start_date = row
appt_end_date = row
length = appt_end_date - appt_start_date
if length not in appt_lengths:
appt_lengths[length] = 1
else:
appt_lengths[length] += 1
``````

with example results:

``````datetime.timedelta(0, 8940): 9,
datetime.timedelta(0, 10740): 11,
datetime.timedelta(0, 12540): 22,
datetime.timedelta(0, 13440): 1,
``````

Using the if in:

``````for row in potus:
appt_start_date = row
appt_end_date = row
length = appt_end_date - appt_start_date
if length not in appt_lengths:
appt_lengths[length] = 1
if length in appt_lengths:
appt_lengths[length] += 1
``````

with example results:

``````datetime.timedelta(0, 8940): 10,
datetime.timedelta(0, 10740): 12,
datetime.timedelta(0, 12540): 23,
datetime.timedelta(0, 13440): 2,``````

Hi The reason is that the first if statement initialise the item in the frequency table and the else add one.

If you have 2 ifs on the same pass it initialise and then add 1 because meet the condition after initialising.

when there is an else it skip that pass and go to the next iteration.

Ah! that does make sense! Thanks for the reply!

Guess I was misunderstanding if/then blocks - somewhere along the lines I started thinking that the first statement it wouldn’t look at the second one. Clearly doesn’t make any sense. Not sure where that idea came from. (the problems of studying alone no one to call me out)

So, playing a little further, if I were to switch the lines as follows, I can get a correct answer. This is consistent with this logic.

ie the following works

``````for row in potus:
appt_start_date = row
appt_end_date = row
length = appt_end_date - appt_start_date
if length in appt_lengths:
appt_lengths[length] += 1
if length not in appt_lengths:
appt_lengths[length] = 1``````
2 Likes