Reputation: 5
I'm a noob and probably dumb, but help is appreciated greatly. I want to know why the code finishes when it executes the "else" statement, I want it to continue the "while" loop.
import random
happy == "no"
while happy == "no":
stat = random.randint(1,50)
print (stat)
happy = input("Are you happy with this?" )
if happy == "yes":
print("Okay moving on. ")
break
else:
print("Please enter a valid answer. ")
Upvotes: 1
Views: 71
Reputation: 5
My friend fixed the code by changing my While Loop. He changed "while happy == "no" to "while True". And he explained that the reason it didn't work before was because the "else" statement was still changing the "happy" variable, because I asked the user to input a string for it in the previous "if" statement.
Upvotes: 0
Reputation: 10712
Your else
should be at the same indent level of if
, and you're trying to make a comparison (==
) in the second line instead of defining the variable happy
to be no
(with =
). This is the fixed code, which I could verify works for me in Python 3.7.4:
import random
happy = "no"
while happy == "no":
stat = random.randint(1,50)
print (stat)
happy = input("Are you happy with this?" )
if happy == "yes":
print("Okay moving on. ")
break
else:
print("Please enter a valid answer. ")
The else
clause in while
is for a specific purpose - somewhat counterintuitive even for non-beginner Python developers (let alone newcomers). You stumbled upon this construct "by accident", that's why your code didn't throw a SyntaxError
and may have mislead you during debugging.
Upvotes: 3
Reputation: 7251
The answer is because your indentation. Indentation is very important in Python.
What you want to do is move the else
statement to the same indentation level of if
, so that way the logic says:
Check if this condition is true, otherwise (else), do this
A simple indent should fix your problem.
import random
happy = "no"
while happy == "no":
stat = random.randint(1,50)
print (stat)
happy = input("Are you happy with this?" )
if happy == "yes":
print("Okay moving on. ")
break
else:
print("Please enter a valid answer. ")
Upvotes: 1