How to make a python program loop/repeat

2.4k views Asked by At

I have a python programming spelling game for children, and I need to make it loop/restart if the player clicks yes once they have finished the game, and exit the program if they click no.

This is the top of my programming.

#Declare Constants and Variables
Score = 0
PlayerAnswer = 0
playOn = 0
while playOn != "Yes":

and this is the end, where I want the player to be able to repeat the game if they click yes on the easygui buttonbox.

playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
if playOn == "Yes":
    Score = 0 #resets score count, if player wants to play again
    
elif playOn == "No":
        easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")
whenever I test it and click yes, the program closes anyway.

3

There are 3 answers

1
jmesolomon On BEST ANSWER
while playOn != "Yes":
   playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
   if playOn == "Yes":
      Score = 0 #resets score count, if player wants to play again

   elif playOn == "No":
     easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")

In Python, the code body needs to be indented for it to be interpreted as inside a code block. In other languages such as C# as long as the codes are inside method{ //code inside here} then the codes will run inside the method.

0
Ken On
while (playOnBool):
    playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
    if playOn == "Yes": playOnBool = True
    else: playOnBool = False

You need to wrap your code with a while loop.

0
David Elson On

The code at the end is not in the 'while' loop at the top.

Since Python goes by indentation, the program will end after the playOn variable is set at the end.

I assume there must be code in the middle, at least a 'pass', otherwise Python will give an indented block error.