Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Dates and Times in Python (2014) Dates and Times Wikipedia Links

More info on 'if' followed by 'else' loop.

Please see code and question below:

import datetime

answer_format = '%m/%d'
link_format = '%B_%d'
link = 'https://en.wikipedia.org/wiki/{}'

print("Welcome to Wikipedia Date Converter! Enter 'QUIT' to quit.")

while True:
    answer = input("What date would you like? Please use the MM/DD format: ")
    if answer.upper() == 'QUIT':
        break
    else:
        continue

    try:
        date = datetime.datetime.strptime(answer, answer_format)
        output = link.format(date.strftime(link_format))
        print(output)
    except ValueError:
        print("That's not a vaild date. Please try again.")

I am still trying to get my head around (easy) 'while True' loops. However I was using Kenneth's wiki code and input 'else' and 'continue' to see what effect it would have and it resulted in never reaching the 'try' block within the 'while True' loop. Can anyone tell me why this is? Am I wrong to think that an 'if' loop implicitly assumes 'else' and 'continue'?

1 Answer

Steven Parker
Steven Parker
231,261 Points

:point_right: No code path can reach the try block.

When you have an if and else combination, one or the other will always be done. In this code, the if leads to break, which ends the loop. And the else leads to continue, which restarts the loop from the top. So there's no way to ever get to anything further down in the loop.

Kenneth's code does not use the else and continue. A continue is not desirable because he wants the rest of the code to execute. Also, when an If performs an action that interrupts the execution flow, like break or continue, an else is never necessary, since the remaining code will only execute when the if condition is false.