How Do I Re-run Code In Python?
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"whileinput("Guess the phrase: ") != phrase:
print("Incorrect.") # Evaluate the input hereprint("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:
defgame(phrase_to_guess):
returninput("Guess the phrase: ") == phrase_to_guess
defmain():
phrase = "hello, world"whilenot 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?")
ifr== "yes"orr== "y":
Loop()
ifr== "n"orr== "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:
while1==1:
[your game here]
input("press any key to start again.")
Or if you want to get fancy:
restart=1while 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.
defmy_game_code():
#codedeffoo():
whileTrue:
my_game_code()
Solution 5:
You could use a simple while
loop:
line = "Y"while line[0] notin ("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?"