Hi, I am creating a game the asks the user if they want to play again at the end.

If the user answers yes, I want python to execute the program again starting from the beginning.

I have tried searching, but could not find anything.

Is there anything in Python that does this?

Thanks!

I don't know if there's a "proper" method of doing this, but I have the code look something like this:

# function to call
def myFunction():
    print "code here"
    return True


# main program
redo = True
while redo == True:
    redo = myFunction()
    # if myFunction does not return True, then the code will end.

That's a pretty basic, although most likely not "proper" or "correct" way of doing it. Hope that helped!

I used to do this is i wanted to restart the file:

exec file("File Name Here")

That will re-open your python program again.

Ah, brilliant! I didn't know that the exec function could be used to execute a python script... thanks - I learned something new! :D

A nice way is to use an exception. An exception allows you to exit the game at any moment, for example you could write this

class RestartException(Exception):
    pass

class QuitException(Exception):
    pass

def askUser():
    # somewhere deep inside the game
    s = raw_input("do you want to restart ?")
    if s == "yes":
        raise RestartException
    elif s == "quit":
        raise QuitException

def main():
    do_play = True
    while do_play:
        do_play = False
        try:
            game = Game() # initializes the game
            game.run()
        except RestartException:
            do_play = True
        except QuitException:
            print "Thank you for playing!"

main()

Thanks guys, I solved the problem!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.