How do I re-run code in Python?

I have this word un-scrambler game that just runs in CMD or the python shell. When the user either guesses the word correctly or incorrectly it says "press any key to play again"

How would I get it to start again?


Solution 1:

Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:

phrase = "hello, world"

while input("Guess the phrase: ") != phrase:
    print("Incorrect.")  # Evaluate the input here
print("Correct")  # If the user is successful

This outputs the following, with my user input shown as well:

Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct

This is obviously quite simple, but the logic sounds like what you're after. A slightly more complex version of which, with defined functions for you to see where your logic would fit in, could be like this:

def game(phrase_to_guess):
    return input("Guess the phrase: ") == phrase_to_guess

def main():
    phrase = "hello, world"
    while not game(phrase):
        print("Incorrect.")
    print("Correct")

main()

The output is identical.

Solution 2:

Even the following Style works!!

Check it out.

def Loop():
    r = raw_input("Would you like to restart this program?")
        if r == "yes" or r == "y":
            Loop()
        if r == "n" or r == "no":
            print "Script terminating. Goodbye."
    Loop()

This is the method of executing the functions (set of statements) repeatedly.

Hope You Like it :) :} :]