Skip to content Skip to sidebar Skip to footer

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'

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 :) :} :]


Solution 3:

Try a loop:

while 1==1:
    [your game here]
    input("press any key to start again.")

Or if you want to get fancy:

restart=1
while restart!="x":
    [your game here]
    input("press any key to start again, or x to exit.")

Solution 4:

Here is a template you can use to re-run a block of code. Think of #code as a placeholder for one or more lines of Python code.

def my_game_code():
    #code

def foo():
    while True:
        my_game_code()

Solution 5:

You could use a simple while loop:

line = "Y"

while line[0] not in ("n", "N"):
    """ game here """
    line = input("Play again (Y/N)?")

hope this helps


Post a Comment for "How Do I Re-run Code In Python?"