Asif Khan
Asif Khan

Reputation: 33

My while loop isn't working

This is just part of my code and i am not sure why my while loop doesn't let the user try again. Please help me!

answer3 = True
while answer3:
    if answer2.lower() == "no" or answer2.lower() == "nah":
        print ("Okay then ... Bye.")
        sys.exit()
    elif answer2 == "Yes".lower() or answer2.lower() == "yeah" or answer2.lower() == "yes":
        print ("Okay then ... \n")
    else:
        print("Please enter a valid answer! Try again!\n")
    break

Upvotes: 2

Views: 8604

Answers (3)

saurabh baid
saurabh baid

Reputation: 1877

Other than removing the break as other answer suggests you need to again get the value of answer2.

Other than that I believe you may also want to break from loop in case answer is yes

answer3 = True
while answer3:
    answer2 = str(input("Enter your answer no/yes:"))
    if answer2.lower() == "no" or answer2.lower() == "nah":
        print ("Okay then ... Bye.")
        sys.exit()
    elif answer2 == "Yes".lower() or answer2.lower() == "yeah" or answer2.lower() == "yes":
        print ("Okay then ... \n")
        sys.exit()
    else:
        print("Please enter a valid answer! Try again!\n")

Upvotes: 0

maki
maki

Reputation: 431

Just remove the break, your problem is that it is stopping after the first iteration.

What is happening is that the break instruction is used to abandon the loop. In your code, you set your first variable to True and expect to continue looping while the condition is not met.

The code just evaluates the conditions and the last sentence (the break) instructs the while to exit, that is what you want to avoid.

Use this code to check the correct behavior:

import sys

answer3 = True
while answer3:
    answer2 = raw_input("introduce your option: ")

    if answer2.lower() == "no" or answer2.lower() == "nah":
        print ("Okay then ... Bye.")
        sys.exit()
    elif answer2 == "Yes".lower() or answer2.lower() == "yeah" or answer2.lower() == "yes":
        print ("Okay then ... \n")
    else:
        print("Please enter a valid answer! Try again!\n")

Upvotes: 1

Pic
Pic

Reputation: 139

The break function exits your while loop, so even if answer3 still has the value True, it will stop the loop after the end of it's first cycle. Remove break and it shall work.

It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

enter image description here

Upvotes: 1

Related Questions