Python: Zero to Hero
Home/The Foundation
Share

Chapter 9: A Beginner Project — Score Keeper

You've covered eight chapters. You know variables, operators, conditionals, loops, lists, functions, and files. That's a real toolkit. Now it's time to use it.

This chapter builds a complete project from scratch — a Score Keeper for a two-team game. You'll plan it, build it piece by piece, test it at each step, and end up with a fully working program that saves results to a file.

The goal isn't just to get the program working. It's to show you how a programmer thinks: start small, add one feature at a time, test constantly, and build up to something complete.

What We're Building

A Score Keeper that:

  • Asks for two team names at the start
  • Keeps a running score for both teams
  • Lets the user add a point for either team after each round
  • Shows the current score after every update
  • Announces the winner when the game ends
  • Saves the final result to a file so there's a record

Simple enough to finish in one sitting. Complex enough to use everything you've learned.

Step 1: Plan Before You Code

Professional programmers don't just start typing. They spend a minute thinking about what the program needs to do and what it needs to know.

What does the program need to store?

  • Two team names (strings)
  • Two scores (integers)

What does the program need to do?

  • Get the team names from the user
  • Repeatedly: ask who scored, update the right score, show the scores
  • Detect when the user wants to end the game
  • Show the winner
  • Save the result to a file

What's the flow?

  1. Get team names
  2. Loop:
    • Show current score
    • Ask: team 1, team 2, or done?
    • If team 1 or 2: add a point and continue
    • If done: break
  3. Show the winner
  4. Save results

That's the whole program, before a single line of code. Writing it out like this — even just as bullet points — saves you from getting lost once the code gets longer.

Step 2: Get the Team Names

Start with just this part. Run it. Make sure it works before moving on.

# score_keeper.py

team1_name = input("Enter name for Team 1: ").strip()
team2_name = input("Enter name for Team 2: ").strip()

print(f"\nGame: {team1_name} vs {team2_name}")
print("Let's play!")

Sample run:

Enter name for Team 1: Eagles
Enter name for Team 2: Tigers

Game: Eagles vs Tigers
Let's play!

Test it. Does it show both names? Good. Move on.

The .strip() removes any accidental spaces the user might type before or after the name. Small detail — big difference when comparing strings later.

Step 3: Set Up the Scores and the Main Loop

Add the score variables and the loop structure.

# score_keeper.py

team1_name = input("Enter name for Team 1: ").strip()
team2_name = input("Enter name for Team 2: ").strip()

team1_score = 0
team2_score = 0

print(f"\nGame: {team1_name} vs {team2_name}")
print("Commands: '1' to score for Team 1, '2' for Team 2, 'q' to quit.\n")

while True:
    print(f"  {team1_name}: {team1_score}  |  {team2_name}: {team2_score}")
    command = input("Who scored? ").strip().lower()

    if command == "1":
        team1_score += 1
        print(f"  Point for {team1_name}!")
    elif command == "2":
        team2_score += 1
        print(f"  Point for {team2_name}!")
    elif command == "q":
        print("\nGame over!")
        break
    else:
        print("  Invalid input. Type '1', '2', or 'q'.")

print(f"\nFinal score — {team1_name}: {team1_score}  |  {team2_name}: {team2_score}")

Sample run:

Enter name for Team 1: Eagles
Enter name for Team 2: Tigers

Game: Eagles vs Tigers
Commands: '1' to score for Team 1, '2' for Team 2, 'q' to quit.

  Eagles: 0  |  Tigers: 0
Who scored? 1
  Point for Eagles!
  Eagles: 1  |  Tigers: 0
Who scored? 2
  Point for Tigers!
  Eagles: 1  |  Tigers: 1
Who scored? 1
  Point for Eagles!
  Eagles: 2  |  Tigers: 1
Who scored? q

Game over!

Final score  Eagles: 2  |  Tigers: 1

Run this. Score a few points for each team. Quit. Does it work exactly as expected? Good. Now we add the winner announcement.

Step 4: Announce the Winner

Add this right after the break but before the final score print — or better, after the final score print. Think about where it belongs logically: after the game ends and after showing the final score.

# After the final score line, add:

if team1_score > team2_score:
    print(f"\nWinner: {team1_name}! Congratulations!")
elif team2_score > team1_score:
    print(f"\nWinner: {team2_name}! Congratulations!")
else:
    print("\nIt's a tie!")

Sample output for a tied game:

Final score  Eagles: 3  |  Tigers: 3

It's a tie!

Three conditions: team1 wins, team2 wins, or a tie. All three handled. Test all three by playing short games with known outcomes.

Step 5: Save the Result to a File

After every game, write the result to results.txt using append mode so each game's result is added to the history, not overwritten.

from datetime import datetime

def save_result(team1_name, team1_score, team2_name, team2_score):
    """Append the game result to results.txt with a timestamp."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")

    if team1_score > team2_score:
        winner = team1_name
    elif team2_score > team1_score:
        winner = team2_name
    else:
        winner = "Tie"

    result_line = (
        f"{timestamp} | "
        f"{team1_name} {team1_score} - {team2_score} {team2_name} | "
        f"Winner: {winner}\n"
    )

    with open("results.txt", "a") as file:
        file.write(result_line)

    print(f"Result saved to results.txt.")

Call this function after announcing the winner:

save_result(team1_name, team1_score, team2_name, team2_score)

Play two or three games. Then open results.txt in a text editor. You'll see something like:

2026-03-09 14:30 | Eagles 3 - 2 Tigers | Winner: Eagles
2026-03-09 14:35 | Lions 1 - 1 Bears | Winner: Tie
2026-03-09 14:40 | Eagles 5 - 3 Lions | Winner: Eagles

A permanent record of every game played.

Step 6: The Complete Program

Here's the full program, clean and organized:

from datetime import datetime


def get_team_names():
    """Ask for two team names and return them."""
    name1 = input("Enter name for Team 1: ").strip()
    name2 = input("Enter name for Team 2: ").strip()
    return name1, name2


def show_score(team1_name, team1_score, team2_name, team2_score):
    """Print the current score."""
    print(f"  {team1_name}: {team1_score}  |  {team2_name}: {team2_score}")


def announce_winner(team1_name, team1_score, team2_name, team2_score):
    """Print the winner or declare a tie."""
    print(f"\nFinal: {team1_name} {team1_score}{team2_name} {team2_score}")
    if team1_score > team2_score:
        print(f"Winner: {team1_name}! Congratulations!")
    elif team2_score > team1_score:
        print(f"Winner: {team2_name}! Congratulations!")
    else:
        print("It's a tie!")


def save_result(team1_name, team1_score, team2_name, team2_score):
    """Append the game result to results.txt with a timestamp."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")

    if team1_score > team2_score:
        winner = team1_name
    elif team2_score > team1_score:
        winner = team2_name
    else:
        winner = "Tie"

    line = (
        f"{timestamp} | "
        f"{team1_name} {team1_score} - {team2_score} {team2_name} | "
        f"Winner: {winner}\n"
    )
    with open("results.txt", "a") as file:
        file.write(line)

    print("Result saved to results.txt.")


def play_game():
    """Run one full game of score keeper."""
    team1_name, team2_name = get_team_names()

    team1_score = 0
    team2_score = 0

    print(f"\nGame: {team1_name} vs {team2_name}")
    print("Type '1' to score for Team 1, '2' for Team 2, 'q' to end the game.\n")

    while True:
        show_score(team1_name, team1_score, team2_name, team2_score)
        command = input("Who scored? ").strip().lower()

        if command == "1":
            team1_score += 1
            print(f"  Point for {team1_name}!\n")
        elif command == "2":
            team2_score += 1
            print(f"  Point for {team2_name}!\n")
        elif command == "q":
            break
        else:
            print("  Invalid. Type '1', '2', or 'q'.\n")

    announce_winner(team1_name, team1_score, team2_name, team2_score)
    save_result(team1_name, team1_score, team2_name, team2_score)


def main():
    """Main entry point — play games until the user quits."""
    print("=== Score Keeper ===\n")

    while True:
        play_game()
        again = input("\nPlay again? (y/n): ").strip().lower()
        if again != "y":
            print("\nThanks for playing. Goodbye!")
            break


main()

A complete, working program. Functions make it readable — each one does exactly one job. main() ties them together.

What the Code Teaches

Look at this program and notice the patterns you've seen in every chapter:

Pattern Where it appears
Variables team1_name, team1_score, team2_name, team2_score
f-strings Every print with team names and scores
if/elif/else Checking who scored, announcing the winner
while True + break The main game loop
Functions with parameters and return get_team_names(), save_result(), etc.
File append mode Saving the result history
datetime module Timestamping each result
.strip().lower() Cleaning user input

There's nothing in this program you haven't seen before. It's just the same building blocks, combined with intention.

How to Extend This Project

Once a program works, the real learning comes from extending it. Here are ideas in order of difficulty:

Beginner extensions:

  • Add a "show history" option that reads and prints results.txt before asking to play again.
  • Add input validation so team names can't be empty.
  • Add a maximum score — the game ends automatically when someone reaches 10 points.

Intermediate extensions:

  • Support more than two teams (use a dictionary mapping name to score).
  • Track how many games each team has won across all sessions (requires more advanced file parsing).
  • Add a rematch feature that swaps which team goes first.

Try one now. Pick the simplest — adding a maximum score — and implement it. You already know everything you need:

MAX_SCORE = 10

# Inside the while loop, after updating the score:
if team1_score >= MAX_SCORE or team2_score >= MAX_SCORE:
    print(f"\nSomeone reached {MAX_SCORE} points!")
    break

Make the change, test it, and see it work. That satisfaction — writing new code that does exactly what you intended — is what programming feels like when things click.

Ideas for Your Own Project

The best way to learn from here is to build something you care about. Here are three project ideas using only what you've learned so far:

Quiz Game

Store questions and answers in two lists. Loop through them. Ask each question with input(). Compare the answer to the correct one. Keep a score. Print results at the end. Bonus: save the high score to a file.

Simple Diary

Ask the user for today's entry using input(). Append it to diary.txt with a date and time stamp. Add an option to show all previous entries by reading and printing the file. This teaches append mode and date formatting.

Unit Converter

Ask what to convert (km to miles, kg to pounds, Celsius to Fahrenheit). Ask for the value. Calculate and print the result. Use a dictionary to store conversion factors. Loop so the user can convert multiple values in one session.

All three use variables, lists, loops, functions, and optionally files. Start with one, get it working, then extend it.

What You Learned in This Chapter

  • Real programs are built in steps: plan, build a little, test, build more.
  • Functions make programs readable — one function, one job.
  • You can use everything from Chapters 1--8 together in one program.
  • while True + break is the standard pattern for interactive menus.
  • File append mode ("a") builds a growing history without overwriting.
  • Extending a working program is the fastest way to deepen your understanding.

What's Next?

Part 1 of this book is complete. You've gone from zero to writing a real, working, file-saving Python program. That's not nothing — that's a foundation most people never build properly.

Part 2 starts now, and it goes deeper. In Chapter 10 you'll learn about strings in depth — all the methods Python gives you to search, slice, transform, and format text. You've been using strings since Chapter 1; it's time to master them.

Your turn: Choose one of the three project ideas above (quiz, diary, or unit converter) and build it from scratch. Don't copy from the book — plan it yourself, write it step by step, test at each step. When it works, add one extension. That's what being a programmer looks like.

© 2026 Abhilash Sahoo. Python: Zero to Hero.