0

I am using python 2.7.1

I would like to be able to restart the game based on user input, so would get the option of restarting, instead of just exit the game and open again. Can someone help me figure out??Thanks

import random

the_number = random.randrange(10)+1

tries = 0
valid = False
while valid == False:
    guess = raw_input("\nTake a guess: ")
    tries += 1
    if guess.isdigit():
        guess = int(guess)
        if guess >= 1 and guess <= 10:
            if guess < the_number:
                print "Your guessed too low"
            elif guess > the_number:
                print "Your guessed too high"
            elif tries <= 3 and guess == the_number:
                print "\n\t\tCongratulations!"
                print "You only took",tries,"tries!"
                break
            else:
                print "\nYou guessed it! The number was", the_number,"\n"
                print "you took",tries,"tries!"
                break
        else:
            print "Sorry, only between number 1 to 10"
    else:
        print "Error,enter a numeric guess"
        print "Only between number 1 to 10"
    if tries == 3 and guess != the_number:
        print "\nYou didn't guess the number in 3 tries, but you still can continue"
        continue
    while tries > 3 and guess != the_number:
        q = raw_input("\nGive up??\t(yes/no)")
        q = q.lower()
        if (q != "yes") and (q != "no"):
            print "Only yes or no"
            continue
        if q != "no":
            print "The number is", the_number
            valid = True
            break
        else:
            break
phhnk
  • 121
  • 2
  • 4
  • 10

3 Answers3

3

Put your current code in a function, such as play_game or whatever. Then write a loop that invokes the function until the user has had enough. For example:

def global_thermonuclear_war():
    print "Boom!"

while raw_input("Shall we play a game? [y|n] ") == 'y':
    global_thermonuclear_war()
FMc
  • 41,963
  • 13
  • 79
  • 132
1

Add a variable, name it something like continue, and initialize it to true. then wrap your whole thing in a while(continue) loop, and at the end of the loop print play again? and accept a user input, setting continue based on what they answer.

  • 4
    `continue` is a poor choice for a variable name since it's [already a Python keyword](http://docs.python.org/reference/simple_stmts.html#the-continue-statement). – Greg Hewgill Apr 12 '11 at 01:42
  • :D sorry, didn't know that... still need to get around to learning python myself –  Apr 12 '11 at 02:21
0
while True:
    play_guessing_game()
    user = raw_input("Play again? (Y/n) ")
    again = "yes".startswith(user.strip().lower())
    if not again:
        break

... the "yes".startswith() bit makes it accept inputs like 'Ye' or ' yeS' or just hitting Enter.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99