1

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?

0

9 Answers 9

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Trufa I figured guessing on the first try wouldn't show all the output, and I didn't want it to look like I was cheating by scoring on the second guess...
@Ricardo Still, it is pretty amazing! My +1 to your reasoning :)))
5

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

1 Comment

To make it run in python 3.x, change raw_input to input
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]
    restart = input("press any key to start again, or x to exit.")

5 Comments

raw_input() isn't part of Python 3, which I'm assuming the user is using based on the original tag.
Why 1==1 - either while 1: or preferably while True: surely?
Changed to input(), thanks. I have not been keeping my python skills up-to-date, but I figured that even I could handle this question...
No worries. I just wanted to make sure that whatever code sample the OP pastes in works right off the bat.
@JonClements Thanks. It's useful to have it pointed out that I was stuck in the natural language perspective of "while [conditional statement]" as opposed to the more correct perspective of "while [something that evaluates to a boolean]".
2

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()

Comments

1

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

2 Comments

Per the other answers and comments, raw_input() isn't part of Python 3.
sorry didn't notice its about python 3
1
while True:
    print('Your game yada-yada')
    ans=input('''press o to exit or any key to continue
''')
    if ans=='o':
        break

Comments

0

A simple way is also to use boolean values, it is easier to comprehend if you are a beginner (like me). This is what I did for a group project:

 restart = True

 while restart:
     #the program
     restart = raw_input("Press any key to restart or q to quit!")
     if restart == "q":
         restart = False

Comments

0

You need to bury the code block in another code block. Follow the instructions below:

Step 1: Top of code def main()  
Step 2: restart = input("Do you want to play a game?").lower()    
Step 3: Next line; if restart == "yes":    
Step 4: Next line; Indent - main()    
Step 5: Next line; else:  
Step 6: Indent - exit()  
Step 7: Indent all code under def main(): 
Step 8: After all code indent. Type main()

What you are doing is encapsulating the blocks of code into the main variable. The program runs once within main() variable then exits and returns to run the main varible again. Repeating the game. Hope this helps.

def main():    
    import random
    helper= {}
    helper['happy']= ["It is during our darkest moments that we must focus to see the light.",
        "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
        "Do not go where the path may lead, go instead where there is no path and leave a trail.",
        "You will face many defeats in life, but never let yourself be defeated.",
        "The greatest glory in living lies not in never falling, but in rising every time we fall.",
        "In the end, it's not the years in your life that count. It's the life in your years.",
        "Never let the fear of striking out keep you from playing the game.",
        "Life is either a daring adventure or nothing at all."]

    helper['sad']= ["Dont cry because it’s over, smile because it happened.",
        "Be yourself; everyone else is already taken",
        "No one can make you feel inferior without your consent.",
        "It’s not who you are that holds you back, its who you think you're not.",
        "When you reach the end of your rope, tie a knot in it and hang on."]

    answer = input ('How do you feel : ')
    print("Check this out : " , random.choice(helper[answer]))
    restart = input("Do you want a new quote?").lower()
    if restart == "yes":
        main()

    else:
        exit()
main()

1 Comment

Ricardo Altamirano and zimonestones Thank you so much. If I could ask another favor - Can you please write out the question for me. The correct terminology is so vital and helps me compare so I can see my weak spots of knowledge. I dont think it's really "bury the code block in another code block" - What would you say? Thanks!
0

How to rerun a code with user input [yes/no] in python ?

strong text

How to rerun a code with user input [yes/no] in python ? strong text

inside code def main(): try:

    print("Welcome user! I am a smart calculator developed by Kushan\n'//' for Remainder\n'%' for Quotient\n'*' for Multiplication\n'/' for Division\n'^' for power")
    num1 = float(input("Enter 1st number: "))
    op = input("Enter operator: ")
    num2 = float(input("Enter 2nd number: "))


    if op == "+":

        print(num1 + num2)
    elif op =="-":
        print(num1 - num2)
    elif op =="*":
        print(num1 * num2)
    elif op =="/" :
        print(num1 / num2)
    elif op =="%":
        print(num1 % num2)
    elif op =="//":
        print(num1 // num2)
    elif op == "^":
        print(num1 ** num2)
    else:
        print("Invalid number or operator, Valid Operators < *, /, +, -, % , // > ")


except ValueError:

    print("Invalid Input, please input only numbers")

restart = input("Do you want to CALCULATE again? : ")


if restart == "yes":


    main()

else:
    print("Thanks! for calculating keep learning! hope you have a good day :)")


    exit()

main() strong text

You maybe trying to run the entire code with an option for user to type "yes" or "no" to run a program again without running it manually. This is my code for a 'calculator' in which i have used this thing. Is that your solution?

By the way this is a reference link from where i learnt to apply this function. https://www.youtube.com/watch?v=SZdQX4gbql0&t=183s

1 Comment

While this works, it introduces unnecessary recursion (calling the same function from a function). A simple loop would be a more fitting solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.