Build a Resilient Number Guessing Game

Build a replayable Python terminal game with safe input and score tracking.

Introduction

30 Second Summary

A guessing game feels simple until one unexpected entry closes it. A satisfying version keeps responding until the player wins.

In this project, you will build Beat the Bot, a Python terminal game that chooses a hidden number from 1 through 100. Its resilient input loop supports replayable rounds with a session best score.

What You'll Build

You play several rounds of Beat the Bot in the terminal with instant hints plus a session best score to beat.

By the end of this project, you'll have:

  • A playable round where each guess gets an immediate too high, too low, or correct result.
  • A resilient guessing experience that corrects text or out-of-range entries without crashing.
  • A replayable game that remembers the best attempt count from the current session.
  • Secret Mission: Add easy, medium, and hard modes with distinct number ranges and guess limits.

Are there any prerequisites?

You need a computer running Windows 10 or newer plus basic familiarity with running a small Python program. The project verifies Python 3.15.2 and sets up Visual Studio Code if your current editor is different.

Before We Start

A clear purpose gives every decision in Beat the Bot a direction. This checkpoint captures why building a resilient terminal number guessing game matters to you before the hands-on work begins.

Set Up the Game Workspace

Beat the Bot needs a predictable workspace before its game logic can grow. A verified Python runtime removes setup uncertainty from every run.

Visual Studio Code keeps your script beside the terminal that runs it. You'll confirm the editor first. You'll then verify Python 3.15.2 before printing the game title.

In this step, get ready to:
  • Confirm Visual Studio Code is ready on Windows.
  • Verify that Python 3.15.2 is available.
  • Create a runnable my-script.py file that prints the game title.
Set up Visual Studio Code

A consistent editor keeps every instruction aligned with what you see. Visual Studio Code also includes the terminal you'll use to run the game.

Why Visual Studio Code?

Your existing editor may already run Python. Visual Studio Code gives this project one consistent file view and terminal workflow.

✔️ Visual Studio Code is installed

  • Press the Windows key to open Windows search.
  • Type Visual Studio Code.
  • Press Enter to open Visual Studio Code.

You'll see the Visual Studio Code window. The editor is ready for your game folder.

ⓧ It is not installed yet

The Windows User setup installs Visual Studio Code for your account. It does not require administrator permissions.

  • Open the official Visual Studio Code Windows setup guide.
  • Download the User setup for Windows.
  • Run the downloaded installer.
  • Follow the installer prompts using the default choices.
  • Close every open Command Prompt window after installation.
  • Press the Windows key to open Windows search.
  • Type Command Prompt.
  • Press Enter to open a fresh Command Prompt.
  • Verify that Visual Studio Code can open the current folder by running:
code .

What does this command do?

The code command launches Visual Studio Code. The . value opens the current folder in the editor.

You'll see Visual Studio Code open with the current folder in its Explorer sidebar.

Visual Studio Code did not open?

A Command Prompt opened before installation may not recognize the new command. Close it before opening a fresh Command Prompt from Windows search.

Run the command again from the fresh window. Help me troubleshoot the Visual Studio Code command on Windows.

Your project folder gives every file a known home. Opening that folder also makes it the starting location for Visual Studio Code's integrated terminal.

  • Click File in the Visual Studio Code menu bar.
  • Select Open Folder....
  • Select your Desktop in the folder picker.
  • Select New Folder.
  • Enter beat-the-bot as the folder name.
  • Select Select Folder.
  • Select Yes, I trust the authors if the Workspace Trust dialog appears.

You'll see beat-the-bot at the top of the Explorer sidebar. Your game now has a dedicated workspace.

Verify Python 3.15.2

The Python version controls how your script runs. Confirming the project version now keeps every later result consistent.

  • Click View in the Visual Studio Code menu bar.
  • Select Terminal.

You'll see the integrated terminal open inside Visual Studio Code. It starts in your beat-the-bot folder.

  • List the Python runtimes available on your computer by running:
py list

What does this command show?

The Python install manager uses py list to show the available runtimes. The listing also identifies the current runtime.

✔️ I see version 3.15.2

Great, Python 3.15.2 is available. Your game has the runtime it needs.

ⓧ I see an older version

The listed runtime is older than the project version. Install the current Python 3.15 runtime beside it.

The download can take a few minutes. A quiet terminal during that time is expected.

  • Install the required runtime by running:
py install 3.15

What does this command install?

The 3.15 tag requests the latest available Python 3.15 runtime. The runtime list should include 3.15.2 after installation.

  • Run the runtime listing command from above again.

You'll now see Python 3.15.2 in the list.

Runtime installation failed?

Check that your computer is connected to the internet. The install manager downloads the runtime during this command.

Try the command once more after confirming the connection. Help me troubleshoot the Python runtime installation.

ⓧ Command not found

The runtime listing command needs the Python install manager. You can get it from Python's official Windows downloads page.

  • Open the official Python downloads for Windows page.
  • Download the Python install manager.
  • Run the downloaded installer.
  • Select Install when the installer asks how to continue.
  • Close the current integrated terminal.
  • Click View in the Visual Studio Code menu bar.
  • Select Terminal to open a fresh integrated terminal.

The runtime download can take a few minutes. A quiet terminal during that time is expected.

  • Install the required runtime by running:
py install 3.15

What happens during installation?

The install manager downloads the latest Python 3.15 runtime. It then registers that runtime for the py command.

  • Run the runtime listing command from above again.

You'll see Python 3.15.2 in the list.

The command is still unavailable?

Close Visual Studio Code completely after installing the manager. Reopen the beat-the-bot folder before opening a fresh integrated terminal.

Run the listing command again from the fresh terminal. Help me fix the Python install manager command.

Create your first runnable script

A tiny visible result proves that the editor and runtime are connected. The first script prints the game's title in the terminal.

  • Select the Explorer icon in the left Activity Bar.
  • Select New File... in the Explorer view.
  • Enter my-script.py as the file name.
  • Press Enter to create the file.
  • Add the game title by pasting this code into my-script.py:
print("BEAT THE BOT")

What does this code do?

The print() function sends text to the terminal. The quoted BEAT THE BOT value becomes the first visible screen of your game.

  • Press Ctrl+S to save my-script.py.
  • Form a prediction about the exact title the terminal will print.
  • Run the saved script in the integrated terminal by running:
python my-script.py

What does this command do?

The python command launches the default runtime. It executes the code stored in my-script.py.

You'll see BEAT THE BOT in the integrated terminal. Your first Beat the Bot screen is now running from the file you created.

Title missing from the terminal?

  • Confirm that my-script.py is saved in the beat-the-bot folder.
  • Confirm that the integrated terminal is open in the beat-the-bot folder.

Run the script again after correcting the location. Help me troubleshoot my first Python script.

✔️ Awesome, I've got everything!

Great. Double check that my-script.py is saved. Your integrated terminal should show the game title.

ⓧ I'd like to double check the full code

Compare your complete my-script.py file with this reference:

print("BEAT THE BOT")

Your workspace is ready to run every change you make. Next, you'll turn this title into a one-shot number guessing game.

Build a One-Shot Guess

Your workspace already runs a Python file inside Visual Studio Code. Now you'll turn that static title into an interactive guessing game.

A one-guess version gives the player immediate feedback. A wrong guess also ends the program after that first hint, which exposes the limitation you'll investigate in this step.

In this step, get ready to:
  • Choose a secret integer from 1 through 100.
  • Read one numeric guess and compare it with the secret number.
  • Test a guaranteed low guess and observe the one-shot limitation.
Choose a secret and capture one guess

The random module can choose an integer from an inclusive range. Two constants give that range one source of truth throughout the script.

  • Return to my-script.py in the editor.
  • Select the existing print("BEAT THE BOT") line.
  • Replace the selected line by pasting this code:
import random

MIN_NUMBER = 1
MAX_NUMBER = 100

secret_number = random.randint(MIN_NUMBER, MAX_NUMBER)
guess = int(input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: "))

What does this code do?

  • The import random line makes Python's random number tools available to the script.
  • The MIN_NUMBER constant stores the lowest possible secret number.
  • The MAX_NUMBER constant stores the highest possible secret number.
  • The random.randint(MIN_NUMBER, MAX_NUMBER) call can choose either endpoint of the range.
  • The input() call displays the prompt and returns the player's entry as text.
  • The int() call converts that text into an integer for the upcoming comparison.
  • Save my-script.py.
  • Return to the integrated terminal from the previous step.
  • Launch the partial one-shot game by running this command:
python my-script.py

What does this command do?

The python command runs the saved instructions in my-script.py. The script chooses its secret number before displaying the input prompt.

  • Enter 50 at the number prompt.

You'll see the number prompt before the terminal returns to its command prompt. That visible prompt proves my-script.py now collects a numeric guess from the player.

Prompt not appearing?

  • Confirm that you saved my-script.py after replacing the original title line.
  • Check that the integrated terminal still points to the project folder containing my-script.py.

Help me troubleshoot why my Python script does not display its number prompt.

Compare and test one guess

A set of comparisons can route the player's number to one of three messages. Python checks the conditions in order until it finds the matching branch.

  • Switch back to my-script.py in the editor.
  • Place the cursor on a new line below the guess = int(input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: ")) line.
  • Add the comparison block by pasting this code:
if guess < secret_number:
    print("Too low!")
elif guess > secret_number:
    print("Too high!")
else:
    print("You got it!")

How do the comparisons work?

  • The if branch handles guesses below the secret number.
  • The elif branch handles guesses above the secret number.
  • The else branch runs when the two numbers match.
  • Only one branch prints a message during each run.
  • Save my-script.py.
  • Return to the integrated terminal from earlier.

Before you run this test, what do you expect the game to do after it prints its hint?

  • Start the updated game by running this command:
python my-script.py

What does this test run?

This command launches the saved version with the new comparison block. The script waits at its input prompt before choosing which message to print.

  • Enter 0 at the number prompt.

You'll see Too low!. The terminal then returns to its command prompt instead of asking for another guess.

You have built the first playable slice of Beat the Bot. Its immediate ending is the intended limitation of this one-shot version.

Didn't See Too Low?

  • Confirm that you entered 0 after the script displayed its number prompt.
  • Check that the first condition reads if guess < secret_number:.
  • Match the indentation of each print() line with the code above.

Help me debug why entering zero does not print Too low.

✔️ Awesome, I've got everything!

Great. Double check that my-script.py is saved and entering 0 prints Too low! before the program ends.

ⓧ I'd like to double check the full code

Here is the complete my-script.py file for this step. Make sure yours matches exactly:

import random

MIN_NUMBER = 1
MAX_NUMBER = 100

secret_number = random.randint(MIN_NUMBER, MAX_NUMBER)
guess = int(input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: "))

if guess < secret_number:
    print("Too low!")
elif guess > secret_number:
    print("Too high!")
else:
    print("You got it!")

Your game now chooses a secret number and judges one guess. Next, you'll keep the round alive until the player finds the secret.

Keep the Player Guessing

Your one-shot game already gives an accurate hint for a single guess. A wrong answer still ends the round.

In this step, you'll use a loop to keep the challenge alive until the player succeeds. You'll count every numeric guess so the win has a measurable score.

In this step, get ready to:
  • Wrap the guess logic in a loop that waits for a correct answer.
  • Count every numeric guess with attempts.
  • Print the total after the player wins.
Build the repeating round

A while True loop repeats the guessing logic until the program reaches break. The attempts variable records each numeric guess during that round.

  • In my-script.py, select everything from secret_number = random.randint(MIN_NUMBER, MAX_NUMBER) through the final print("You got it!") line.
  • Replace the selected one-shot logic with this repeating round:
secret_number = random.randint(MIN_NUMBER, MAX_NUMBER)
attempts = 0

while True:
    guess = int(input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: "))
    attempts += 1

    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print("You got it!")
        break

print(f"You got it in {attempts} attempts!")

What does this code do?

  • The attempts counter starts at 0 for each new round.
  • The while True block asks for another guess after every high or low hint.
  • The attempts += 1 line counts each entry that int() converts successfully.
  • The break statement ends the loop only after the player finds the secret number.
  • The final print() sits outside the loop. It runs once after the win.
  • Save my-script.py.

Before you run the game, do you expect one wrong guess to end the round this time?

  • Start the updated game in the integrated terminal from earlier by running this command:
python my-script.py

What should happen now?

The command starts a new round with a fresh secret number. The terminal waits for your first guess.

  • Enter 0 at the prompt.
  • Follow the next prompt with another whole-number guess.
  • Continue using each hint until your guess matches the secret number.

You'll see Too low! after 0. The game asks for another guess instead of ending.

That's the loop working. Your game now survives every wrong numeric guess before reporting the winning attempt total.

Does the game stop too early?

  • Check that every line from guess = int(input(...)) through break is indented under while True.
  • Check that break is indented inside the final else block.
  • Help me fix my guessing loop.
Verify a complete round

The first run proved that the game repeats. A fresh round now checks that the final total includes every numeric guess.

Before you run the game again, how many attempts do you expect after two guaranteed wrong guesses plus the guesses needed to find the secret?

  • Start a fresh round by running this command:
python my-script.py

What does this check prove?

This run creates a new secret number. Your next entries test repeated feedback before the final score appears.

  • Enter 0 as your first guess.
  • Enter 101 as your second guess.
  • Use the high and low hints to narrow the possible number.
  • Keep entering whole numbers until you find the secret.

You'll see Too low! after 0. You'll see Too high! after 101.

The game asks again after both entries. Once you find the secret, the terminal reports the total number of attempts.

Solid work. Your terminal game now stays active through wrong numeric guesses and turns a completed round into a score.

Does the attempt total look wrong?

  • Check that attempts = 0 appears before while True.
  • Check that attempts += 1 appears immediately after the input line.
  • Check that the final score line has no indentation.
  • Help me correct my attempt counter.

✔️ Awesome, I've got everything!

Great. Double check that you saved my-script.py and completed a round with at least two wrong guesses.

ⓧ I'd like to double check the full code

Compare your complete my-script.py file with this version:

import random

MIN_NUMBER = 1
MAX_NUMBER = 100

secret_number = random.randint(MIN_NUMBER, MAX_NUMBER)
attempts = 0

while True:
    guess = int(input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: "))
    attempts += 1

    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print("You got it!")
        break

print(f"You got it in {attempts} attempts!")

Your game now keeps the player guessing until they win. Next, you'll protect that loop from text entries and numbers outside the allowed range.

Make Every Guess Safe

Your game now keeps the challenge alive until the player finds the secret number. Every new entry reaches the conversion line inside that loop.

The current conversion line sends every response directly into int(). Text such as banana triggers a ValueError before the loop can continue.

You'll reproduce that crash first. Targeted exception handling and range validation will then keep the game responsive.

In this step, get ready to:
  • Reproduce the crash caused by non-numeric input.
  • Create a function that returns only valid guesses.
  • Keep invalid guesses from ending the round.
Reproduce the text-input crash

The current loop assumes that every player enters digits. Running the game with text exposes exactly where that assumption breaks.

  • Save my-script.py.

Before you run the game, do you think the loop can recover after int() receives a word?

  • Start the current game by running this command:
python my-script.py

What does this command do?

This command launches the saved my-script.py file. The terminal stays connected to the program so it can receive your guess.

  • Enter banana at the number prompt.

This crash is intentional

You'll see a traceback that mentions ValueError. The int() conversion cannot turn banana into an integer.

The exception has no handler yet. Python stops the script before the loop can ask for another guess.

Build the safe input loop

A dedicated validation function can keep asking until the player provides a usable number. It also keeps the main game loop focused on hints and attempts.

  • In my-script.py, place your cursor below MAX_NUMBER = 100.
  • Add the validation function by pasting this code:
def get_valid_guess():
    while True:
        try:
            guess = int(
                input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: ")
            )
        except ValueError:
            print("Please enter a whole number.")
            continue

        if MIN_NUMBER <= guess <= MAX_NUMBER:
            return guess

        print(f"Your guess must be from {MIN_NUMBER} to {MAX_NUMBER}.")

What does this code do?

  • The while True loop keeps validation active until the function returns a usable guess.
  • The try block attempts to convert the player's entry into an integer.
  • The except ValueError: block catches text input. The continue statement restarts the validation loop.
  • The MIN_NUMBER <= guess <= MAX_NUMBER check returns only guesses inside the game's range.
  • Find guess = int(input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: ")) inside the game loop.
  • Replace that line with guess = get_valid_guess().
  • Save my-script.py.

Before you rerun the game, do you think banana can still end the script?

  • Test the new validation function by running this command:
python my-script.py

What does this test run?

This command runs the saved game with get_valid_guess() connected to the main loop. The terminal waits for each test entry.

  • Enter banana at the first prompt.
  • Enter 0 at the next prompt.
  • Enter 50 at the next prompt.
  • Follow the hints until you find the secret number.

You'll see Please enter a whole number. after banana. You'll see Your guess must be from 1 to 100. after 0.

The prompt returns after each correction. That is the risky input path handled: invalid entries no longer destroy the round.

Does the game still stop?

Check that the game loop calls get_valid_guess(). A remaining call to int(input(...)) can still trigger the original crash.

Check that get_valid_guess() appears above secret_number. Python must define the function before the game calls it.

Help me debug my safe guess function.

Confirm invalid guesses recover

The attempt counter increases only after get_valid_guess() returns. Moving the win message into the matching branch keeps the final attempt count beside the successful guess.

  • Find print("You got it!") inside the else branch.
  • Replace it with print(f"You got it in {attempts} attempts!").
  • Delete the final print(f"You got it in {attempts} attempts!") line below the loop.
  • Save my-script.py.

Before you run this final check, do you think either invalid entry can reach attempts += 1?

  • Run the finished safe-input version with this command:
python my-script.py

What does this final check prove?

This command launches the revised game from the integrated terminal. The next entries test both failure paths before an accepted guess reaches the attempt counter.

  • Enter banana at the first prompt.
  • Enter 0 at the next prompt.
  • Enter 50 at the next prompt.
  • Follow the hints until you guess correctly.

You'll see one correction for banana. You'll see a different correction for 0.

The game asks again without showing a traceback. When you win, the terminal reports the number of accepted guesses.

You have made every guess safe. The game now recovers from bad input while preserving the player's progress.

✔️ Awesome, I've got everything!

Great. Double check that my-script.py is saved. Confirm that text and out-of-range numbers both return you to the prompt.

ⓧ I'd like to double check the full code

Compare your complete my-script.py file with this version:

import random

MIN_NUMBER = 1
MAX_NUMBER = 100


def get_valid_guess():
    while True:
        try:
            guess = int(
                input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: ")
            )
        except ValueError:
            print("Please enter a whole number.")
            continue

        if MIN_NUMBER <= guess <= MAX_NUMBER:
            return guess

        print(f"Your guess must be from {MIN_NUMBER} to {MAX_NUMBER}.")


secret_number = random.randint(MIN_NUMBER, MAX_NUMBER)
attempts = 0

while True:
    guess = get_valid_guess()
    attempts += 1

    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print(f"You got it in {attempts} attempts!")
        break

Your input loop is resilient. Next, you'll organize the game into reusable functions so players can start new rounds and track their best score.

Add Replay and a Best Score

Your game now keeps asking for a guess until the player wins. It also handles text or out-of-range entries without crashing.

A single completed round cannot demonstrate reusable functions or session state. An outer replay loop lets one session run several rounds while preserving its best score.

In this step, get ready to:
  • Move one validated round into play_game().
  • Build main() to replay rounds while tracking the session's best score.
  • Normalize the replay answer before launching the finished game through an entry-point guard.
Move one round into a function

The current game logic runs as soon as the script starts. A named round function makes that logic reusable from a larger session loop.

  • In the my-script.py tab from earlier in Visual Studio Code, select the existing game block from secret_number = random.randint(MIN_NUMBER, MAX_NUMBER) through its final break.
  • Replace the selected block with the reusable round function by pasting this code:
def play_game():
    secret_number = random.randint(MIN_NUMBER, MAX_NUMBER)
    attempts = 0

    print("\nBEAT THE BOT")
    print(f"I chose a number from {MIN_NUMBER} to {MAX_NUMBER}.")

    while True:
        guess = get_valid_guess()
        attempts += 1

        if guess < secret_number:
            print("Too low!")
        elif guess > secret_number:
            print("Too high!")
        else:
            print(f"You got it in {attempts} attempts!")
            return attempts

What does this function do?

  • The function creates a new secret number each time a round begins.
  • The attempt counter belongs to one round, so every replay starts from zero.
  • Returning attempts gives the session loop a score it can compare after the player wins.

The round now has a reusable name. A temporary direct call provides a quick test before you build the full session loop.

  • Add a temporary call on a blank line below play_game() by pasting:
play_game()

Why call the function here?

This line asks Python to run one complete round. The returned attempt count is ignored for this temporary test.

  • Save my-script.py.

Before you run the script, do you expect the extracted round to behave differently from the previous version?

  • Run one extracted round in the integrated terminal from earlier by running this command:
python my-script.py

What should you see?

You will see BEAT THE BOT followed by the selected number range. The game keeps accepting validated guesses until your winning guess produces an attempt count.

Does the script stop immediately?

Check that the temporary play_game() call sits below the complete function. Indentation inside the function must remain four spaces deep.

Help me fix my extracted play_game() function.

Add the replay and score loop

A session needs one place to coordinate repeated rounds. The main() function keeps the best score alive while each call to play_game() creates a fresh round.

  • Place your cursor immediately above the temporary play_game() call at the bottom of my-script.py.
  • Insert the session function by pasting this code:
def main():
    best_score = None

    while True:
        attempts = play_game()

        if best_score is None or attempts < best_score:
            best_score = attempts
            print(f"New best score: {best_score}")
        else:
            print(f"Best score this session: {best_score}")

        play_again = input("Play again? (y/n): ").strip().lower()
        if play_again != "y":
            print("Thanks for playing Beat the Bot!")
            break

How does the session work?

  • The value None means the session has no score before its first completed round.
  • Each returned attempt count either becomes a new best score or leaves the existing score unchanged.
  • The replay response loses surrounding whitespace through strip().
  • The replay response becomes lowercase through lower(), so an uppercase answer works consistently.
  • Save my-script.py.
  • Check the new function for syntax errors by running this command:
python my-script.py

What does this check prove?

You will still play one round because the temporary play_game() call remains at the bottom. Reaching the winning message without a traceback confirms that main() was defined successfully.

Seeing a syntax or indentation error?

Check that every line inside main() uses four spaces per indentation level. The replay prompt belongs inside the outer while True loop.

Help me fix the structure of my main() function.

The new session function is ready. Replacing the temporary round call with a session call lets the replay loop take control.

  • Find this temporary line at the bottom of my-script.py:
play_game()

What does the current call run?

The current line runs one round directly. It bypasses the replay prompt and best-score logic inside main().

  • Replace the temporary round call with this session call:
main()

What changes after this swap?

The script now enters the outer session loop. Every completed round produces a score before the replay prompt appears.

  • Save my-script.py.

Before you start the session, which round do you think will become your best score?

  • Start the replay session by running this command:
python my-script.py

What happens during this run?

The first completed round sets a new best score. Later rounds replace it only when they use fewer attempts.

  • Finish the first round by finding its secret number.
  • Enter y at the first replay prompt.
  • Finish the second round by finding its new secret number.
  • Enter n at the second replay prompt.

You will see a score message after each round. The session ends with Thanks for playing Beat the Bot!.

Does the game stop after one round?

Confirm that the bottom of the file calls main(). Check that the replay prompt remains inside the outer loop.

Help me debug the replay loop in my number guessing game.

Protect the script entry point

An entry-point guard launches main() when this file runs as a script. It also keeps the functions available without starting a game automatically if the file is imported elsewhere.

  • Locate this direct call at the bottom of my-script.py:
main()

Why replace the direct call?

A direct call starts the session whenever the file is loaded. The entry-point guard limits that automatic start to script launches.

  • Replace the direct call with the standard entry-point guard:
if __name__ == "__main__":
    main()

How does the guard work?

Python assigns "__main__" to __name__ when you launch this file directly. The condition then calls main().

  • Save my-script.py.
  • Finish the first verification round by finding its secret number.
  • Enter y at the first replay prompt.
  • Finish the second verification round by finding its secret number.
  • Enter n at the second replay prompt.

Before you launch the final version, do you expect the best score to reset between rounds or remain available for the whole session?

  • Launch the completed game in the integrated terminal by running this command:
python my-script.py

What should you see?

You will play two complete rounds within one session. The terminal shows either a new best score or the existing session best after each win.

After you enter n, the game ends with Thanks for playing Beat the Bot!.

Missing the best score or farewell?

Confirm that best_score = None sits above the outer loop. Check that the farewell and break lines belong to the replay condition.

Help me compare my completed game with the expected replay and score flow.

You have turned one safe round into a replayable game. The session now remembers its strongest score until the player exits.

✔️ Awesome, I've got everything!

Your saved my-script.py now runs multiple rounds, tracks the best score, and exits with the farewell message.

ⓧ I'd like to double check the full code

The complete my-script.py file is shown below for comparison.

import random

MIN_NUMBER = 1
MAX_NUMBER = 100


def get_valid_guess():
    while True:
        try:
            guess = int(
                input(f"Enter a number from {MIN_NUMBER} to {MAX_NUMBER}: ")
            )
        except ValueError:
            print("Please enter a whole number.")
            continue

        if MIN_NUMBER <= guess <= MAX_NUMBER:
            return guess

        print(f"Your guess must be from {MIN_NUMBER} to {MAX_NUMBER}.")


def play_game():
    secret_number = random.randint(MIN_NUMBER, MAX_NUMBER)
    attempts = 0

    print("\nBEAT THE BOT")
    print(f"I chose a number from {MIN_NUMBER} to {MAX_NUMBER}.")

    while True:
        guess = get_valid_guess()
        attempts += 1

        if guess < secret_number:
            print("Too low!")
        elif guess > secret_number:
            print("Too high!")
        else:
            print(f"You got it in {attempts} attempts!")
            return attempts


def main():
    best_score = None

    while True:
        attempts = play_game()

        if best_score is None or attempts < best_score:
            best_score = attempts
            print(f"New best score: {best_score}")
        else:
            print(f"Best score this session: {best_score}")

        play_again = input("Play again? (y/n): ").strip().lower()
        if play_again != "y":
            print("Thanks for playing Beat the Bot!")
            break


if __name__ == "__main__":
    main()

Secret mission

Add Difficulty Modes

Give Beat the Bot three distinct difficulty modes. Each mode changes the secret number range plus the number of guesses available.

Clean Up Your Resources

Clean Up Your Resources

Choose whether to keep your game ready, pause your local session, or delete the game file. This project runs entirely on your Windows computer, so there are no ongoing costs.

Resources you used:

  • Local game file my-script.py in the current project folder.

Keep everything running

No action needed. Choose this if you want to keep playing or build more features.

  • Keep my-script.py in the current project folder.
  • Return to the integrated terminal from earlier whenever you want to play again.

Pause - I'll come back to this later

Stop the local game session to free the memory used by your editor. Your game file stays ready for later.

  • Press Ctrl+C in the integrated terminal if the game is waiting for input.
  • Close Visual Studio Code.

Delete - I don't want to use this again

Deleting the game file is permanent. Your installed tools stay untouched.

  • Return to the integrated terminal from earlier.
  • Delete my-script.py by running this command:
del my-script.py

What does this remove?

This command removes only my-script.py from the terminal's current folder. It leaves your installed tools unchanged.

  • Check the file list in Visual Studio Code for my-script.py.

You should no longer see my-script.py in the current project folder.

Still See the Game File?

  • Confirm that the integrated terminal is still in the project folder that contains my-script.py.
  • Check that the filename is exactly my-script.py.

Help me work out why the game file was not deleted.

Nice Work!

Nice Work!

You pulled it off! Beat the Bot is now a resilient Python terminal game.

You've learned how to:

  • Built a randomized game loop with immediate high or low hints. The winning message reports the final attempt count.
  • Reproduced a real input crash before adding input validation with except ValueError:. Range checks now keep every guess between the allowed minimum and maximum.
  • Organized the game into reusable functions for input handling, individual rounds, and the full application. Session state preserves the best score across replayed rounds.
  • Added difficulty modes through the Secret Mission. Each mode now uses its own number range and guess limit.

Ready to quiz yourself?