(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 programming, lol)
CodePudding user response:
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")
CodePudding user response:
You can read the Python Control Flow Documentation. "break", like its name, breaks the loop and finish your loop. You can use pass
if you want to see no action, or you can use continue
to step up the next iteration.
The difference between continue
and pass
is the type of going on the loop. For example:
l = [1, 2, 3, 4, 5]
for i in l:
if i > 3:
pass
print(i) # output will be 1 2 3 4 5
Let's try this function with continue:
l = [1, 2, 3, 4, 5]
for i in l:
if i > 3:
continue
print(i) # output will be 1 2 3
Summarily, you can make the loop work with 2 ways:
continue: Finish the loop and don't keep going the codes under it.
pass: Do nothing and continue the loop and keep going the codes under it.