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

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.