r/learnpython • • Oct 29 '26

Number Guessing Game Won't Loop When Prompted

**Question Answered**

Thank you everyone for all the advice and suggestions, I think I have it working the way I need it to, and I have a lot of great stuff to look into so I can clean up and refine my future coding as I learn more. Very thankful and appreciative!

**

Hello, I'm trying to learn Python and am having trouble with my number guessing game assignment. I need the game to be able to loop and replay the game when the player is prompted to at the end, but the only part of it that works is when the player doesn't want to continue playing and the code stops. Could I please have some help figuring out a better way to write the code to replay? Thank you.

*edited to remove colour tags from code

import os
import random


# high score file
file_path = "highscore.txt"




# welcome banner
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("   Number Guessing Game")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")


print()
player_name = input("Please enter your name: ")
print()



def game_play():
    # game start info for player
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print()
    print("Hello ", player_name + "!")
    print()
    print("Can you guess what number I'm thinking of?")
    print("It's between 1 and 100.")
    print("I'll give you 10 guesses!")
    print()
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



    # Check if the file exists
    if os.path.isfile(file_path):
        with open(file_path, "r") as file:
            content = file.read()
            print()
            print("Previous Best:")
            print()
            print(content)
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    else:
        print(f"Error: The file '{file_path}' does not exist.")
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



    # game parameters
    lowest_number = 1
    highest_number = 100
    max_attempts = 10
    
    # the stats the game starts with
    guess = 0
    attempts = 0
    
    # random number selection
    secret_number = random.randint(lowest_number, highest_number)
    # print number below for DEBUG ONLY
    print("    *secret number is: " + str(secret_number))


    while True:
        # game mechanics
        while guess != secret_number:
            guess = int(input("Guess a number: "))
            attempts = attempts + 1
            print("Number of attempts: ", attempts)



            # ensure number entered is within range
            if guess < 1 or guess > 100:
                print("Please enter a number between 1 and 100.")
    


            # too high and too low        
            elif guess < secret_number and lowest_number:
                print("Nope, too low!")
                print()
        
            elif guess > secret_number:
                print("Nope, too high!")
                print()


    
            # game over for max attempts reached
            elif attempts == max_attempts and guess != secret_number:
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print()
                print("Uh oh!m You've run out of guesses.")
                print("The number I was thinking of was: ", secret_number)
                print()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                
            # game won
            else:
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                print()
                print("Yaaayyy, well done ", player_name + "!")
                print("You guessed the number I was thinking of, which was:", secret_number, "- and you did so in: " + str(attempts) + " guess(es)!")
                print()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")



        # save player score
        save_score = input("\nWant to save your score? (yes/no:) ")
        if not save_score in ("yes", "no"):
            print("invalid input.")
    
        elif save_score == "yes":
            f = open("highscore.txt", "w")
            f.write(player_name + " - " + str(attempts) + "\n")
            f.close
            break
      
        # continue playing or quit
        answer = input("Play again? (yes/no): ")


        if answer != "yes":
            print()
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print("\nThanks for playing, see ya~\n")
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            


if __name__ == "__main__":
    game_play()
3 Upvotes

24 comments sorted by

View all comments

2

u/socal_nerdtastic Oct 29 '26

You need to reset guess and secret_number if the player wants to replay. The easy way to do that is to move those lines inside the while loop.

while True:

    # the stats the game starts with
    guess = 0
    attempts = 0
    
    # random number selection
    secret_number = random.randint(lowest_number, highest_number)
    # print number below for DEBUG ONLY
    print("    \x1b[90m*secret number is: \x1b[0m" + str(secret_number))

    # game mechanics
    while guess != secret_number:

2

u/Substantial-Hold9159 Oct 30 '26

Ohh I see, I will give that a go, thank you!