Skip to content
Advertisement

While Loop break stops my statement from Printing

(Python/PythonAnywhere) My Code Now:

while True:
    try:
        Question = input("How are you? (Please answer with: ""Good, or Bad"")");
        if Question == ("Good"):
            print("Good to hear!");
            if Question == ("Bad"):
                print("I'm Sorry");
                if Question == ("Bad"):
                    print("Sorry to hear buddy")


            break;
    except:
        if Question == (""):
            print("Please type: Good, or Bad")

This is what goes after: (The code didn’t wanna include this)

name = input("Enter your name: ")
print("Hello", name + "!");

The problem, (from what i can understand) is that the break messes with the print, “I’m Sorry” and when the loop is broken, it also stops the print from printing, moving on to asking the users name. i’ve attempted to change what print it blocks, but that didn’t work, then i tried changing what i had indented, but that didn’t help either. if anyone has an idea how to fix this, i’d love to know.

(P.S I’m a beginner, so if it’s a super easy fix, don’t take shots at me. i’m just trying to learn python, lol)

Advertisement

Answer

You need to indent properly, so that each condition is tested independently.

There’s no need for try/except, since nothing raises any conditions (this is often used when validating numeric input, since int() and float() will raise exceptions if the input isn’t numeric).

You want to break out of the loop when they enter one of the valid choices.

while True:
    Question = input("How are you? (Please answer with: ""Good, or Bad"")");
    if Question == "Good":
        print("Good to hear!");
        break
    if Question == "Bad":
        print("I'm Sorry");
        break
    print("Please type: Good, or Bad")
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement