问题
I'm a newbie at python, so i couldn't figure out how to make this code repeat at the beginning again. Here is my code:
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 5:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
Thanks guys, please respond soon,
回答1:
This must have been the code you've been looking around for
import random
inplay = 0
x = ""
def in_play():
global inplay, guessesTaken
guessesTaken = 0
if inplay == True:
play()
else:
inplay = True
play()
def play():
global guessesTaken
while inplay == True:
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 5:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
elif guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
in_play()
elif guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
in_play()
in_play()
Now that was something basic but for a newbie, we totally know how it feels
Just don't Copy Paste it but try to understand what the code does and why it does it
回答2:
Put your current code in a function, and then invoke it as many times as you want. For example:
import random
def main():
n_games = 5
for n in range(n_games):
play_guessing_game()
def play_guessing_game():
# Your code here.
print("Blah blah")
main()
Even better would be to accept n_games
as a command-line argument (sys.argv[1]
). Even better than that would be to stop writing interactive guessing games (rant: why do people teach this stuff?) and instead learn how to write a function that does binary search.
回答3:
put your code in a function, then create another function that asks the user if he would like to play again.
def main():
game = "your game"
print(game)
play_again()
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) > ")
if play_again == "yes"
main()
if play_again == "no"
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
来源:https://stackoverflow.com/questions/17159485/how-do-you-restart-a-python-guess-a-number-game