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 Challenge Solution

William Burton
William Burton
2,883 Points

The suggested solution does not seem to be very DRY.

My solution combines the prompting of the understanding question and validation of the correctly enter answer as the answer is not actually used for anything later on. The user can enter either 'y' or 'yes' in upper or lower case. Any other response is either considered an invalid response or the 'no' response.

The drawback to this approach is it's not possible to tell the difference between a 'no' answer which is valid and an invalid response but for something this simple, it seems a reasonable compromise as the result is much simpler.

name = input("What's your name? ")

while input(f"{name}, do you understand while loops (yes/no)? ").lower() not in ('y','yes'):
    print("A while loop allows logic to be repeated until a certain condition is met.")
    print("Hope that's understandable now.")
    print("Please enter 'yes' or 'no'.")

print(f"{name}, glad to hear you understand while loops!")

The f-Strings feature is used instead of the .format() method as they are simpler and improve readability (for Python 3.6+).

1 Answer

William Burton
William Burton
2,883 Points

Here's another version that distinguishes between a valid and invalid answer. A 'quit' option was added the user doesn't want to continue:

name = input("What's your name? ")

while True:
    answer = input(f"{name}, do you understand while loops (yes/no/quit)? ").lower()
    if answer in ('y','yes'):
        print(f"{name}, glad to hear you understand while loops!")
        break
    elif answer in ('n','no'):
        print("A while loop allows logic to be repeated until a certain condition is met.")
        print("Hopefully that is understandable now.")
    elif answer in ('q','quit'):
        print("Sorry to see you wish to leave. You may consider reviewing the video again.")
        break
    else:
        print("You must answer 'yes' or 'no'.")