I am writing a hangman game program in python and have run into a problem concerning validating loops. Here is an example of the type of problem:
def loopGet():
condition = True
while condition == True:
userInput = raw_input("Enter a string: ")
# assigns boolean value to condition
condition = ifWon()
# returns condition
return condition
#assigns boolean value
condition = ifLost()
#return condition
return condition
Pretending that ifWon() and ifLost() are already created, this is an example of what’s going and what I am trying to figure out. In my program, even if both return True, the loop ends. If one returns True and the other False, it still ends. I am under the impression that if “condition” returns True, the loop should keep running; yes?
The loop “ends” because the method’s execution stops at the
returnstatement. Since yourreturnstatement is inside your while loop, it appears that you condition is not working.Once you move the
returnstatement outside your loop, you’ll get your expected results.You set a variable to the condition that you want to change. So
isWinner = False, thenwhile isWinner == False:do your loop. IfisWon()returnsTrueorFalse, then in your whileisWinner = isWon(). You don’t needisLost(), as we want the loop to exit when the user has won.