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

I'm not able to exit my while loop...

so I am utilizing the following code:

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

question = input("Do you understand Python while loops? ")

while (question != "yes"): print(input("Do you understand Python while loops? "))

print("Now you get it {}".format(name))


So, when saying yes the first time, it will exit the loop... but if I start with no and THEN say yes after it loops, it will not let me exit the loop... what am i doing wrong :(

2 Answers

When you answer yes the first time, variable question is updated to the condition of your loop before the loop so the loop exits. However if you answer no and the loop is allowed to execute there is no code that updates variable question within the loop. So it will run forever. The following fixes that:

name = input("What's your name? ")
question = ""
while (question != "yes"):
    question = input("Do you understand Python while loops? ")
print("Now you get it {}".format(name))
Majid Bilal
Majid Bilal
3,558 Points

KRIS rightly addresses the issue, you are expecting a particular answer, you will not exit the loop until you've found that answer. You use something like:

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

question = "Do you understand Python while loops? {}, (Yes/No)".format(name)

while True:

    answer = input(question)

    if answer.lower() == 'yes':
        print("That's great, Python is a great language {}".format(name))
        break
    elif answer.lower() == 'no':
        print("You must learn python, it's a great language {}".format(name))
        break
    else:
        print("You didn't enter correct answer {}, try again".format(name))
        continue

The loop will break whether the answer is a yes or a no, otherwise it will indicate to the user that the answer is not what is expected and it will keep looping until a 'yes' or a 'no' is received.