0

I have an almost working code for my number guessing game. It runs completely fine up until the very end when asking the player if they want to play again and they type in "yes"--the Terminal outputs this:

Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no) yes
I'm thinking of a number between 1 and 99!
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no) 

I thought to just put the entire program in a while loop, but I have a few opening questions in the game that should only be asked the first time they run the program, and not every time they want to replay the game. (e.g Whats your name? Do you want to play?) I am not sure how to rerun the program but starting just after those initial questions. With my current code, I am lost at what to write for when the player types in "yes" at the ending to replay the game.

import random
import sys

guesses_taken = 0
number = random.randint(1, 99)

name = input("\nHello, what's your name? ")
print(f"\nNice to meet you, {name}.")

answer = input("Would you like to play a guessing game? (yes/no) ").lower()

while True:
    if answer == "no":
        print("\nToo bad, goodbye!\n") 
        sys.exit()
    elif answer == "yes":
        print(f"\nOkay, let's play!")
        break
    else:
        print("\nSorry, I didn't get that.")

while True:

    print("\nI'm thinking of a number between 1 and 99!")

    while guesses_taken < 6:
        guess = input("Take a guess: ")

        guesses_taken += 1

        if int(guess) > number:
            print("\nYour guess is too high!\n")
        elif int(guess) < number:
            print("\nYour guess is too low!\n")
        else:
            print("\nArgh..you guessed my number! You win! -__-")
            break

    while guesses_taken >= 6:
        print("\nHa ha. You took too many guesses! I win! ^__^")
        break

    again = input("\nWould you like to play again? (yes/no) ")
    if again == "no":
        break

sys.exit()
jzuraf
  • 53
  • 1
  • 11
  • I have also tried defining a function and calling that function at the end, but it did not work for me and kept saying the function was not defined. – jzuraf Oct 02 '19 at 05:01

1 Answers1

0

The variables guesses_taken & number will both retain their values when replaying, which makes for a not-very-interesting game. You need to do something to change that, like -

    again = input("\nWould you like to play again? (yes/no) ")
    if again == "no":
        break
    else:
        guesses_taken = 0
        number = random.randint(1, 99)

Functions, etc can make the code cleaner, but this is the minimal change you need to make to get things working.

ddisisto
  • 431
  • 3
  • 5