124 Chapter 6
Because we start with keep_going = True, the program will
enter the loop at least the first time.
Next we’ll ask the user if they want to keep going. Rather
than make the user enter Y or yes every time they want to play,
let’s make it easier by just asking them to press enter.
answer = input("Hit [Enter] to keep going, any other keys to exit: ")
if answer == "":
keep_going = True
else:
keep_going = False
Here we set a variable answer equal to an input function. Then
we use an if statement to check whether answer == "" to see if the
user pressed enter only or if they pressed other keys before enter.
(The empty string "" tells us the user didn’t type any other char-
acters before pressing enter.) If the user wants to exit, all they
have to do is make answer equal anything other than the empty
string, "". In other words, they just have to press any key or keys
before pressing enter, and the Boolean expression answer == "" will
evaluate to False.
Our if statement checks whether answer == "" is True, and if so,
it stores True in our flag variable keep_going. But do you notice some
repetition there? If answer == "" is True, we assign the value True to
keep_going; if answer == "" evaluates to False, we need to assign the
value False to keep_going.
It would be simpler if we just set keep_going equal to whatever
answer == "" evaluates to. We can replace our code with the follow-
ing, more concise code:
answer = input("Hit [Enter] to keep going, any other keys to exit: ")
keep_going = (answer == "")
The first line hasn’t changed. The second line sets keep_going
equal to the result of the Boolean expression answer == "". If that’s
True, keep_going will be True, and our loop will continue. If that’s
False, keep_going will be False, and our loop will end.
Let’s see the whole loop together:
keep_going = True
while keep_going:
answer = input("Hit [Enter] to keep going, any key to exit: ")
keep_going = (answer == "")