How do I re-run code in Python?

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.

Leave a Comment