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 = 开发者_JAVA百科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
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()
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.
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.
精彩评论