Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Dates and Times in Python 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
216,012 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.