Tuesday, 13 October 2026

Python Programming Through Gamification 6174 : Day 1

Day 1 theme: The 6174 Mystery — Build Your First Python Game

The goal is to help students progress from knowing nothing about programming to building a working number puzzle game. The session introduces programming fundamentals first, then uses the game to teach functions, loops, conditions, debugging and the basics of classes and objects.

1. Day 1 learning outcomes

By the end of the session, students should be able to:

  • Explain how a computer solves a problem using step-by-step instructions.
  • Understand variables, data types, operators, input and output.
  • Use conditions, loops and functions in Python.
  • Explain the Kaprekar routine and implement it in Python.
  • Test a program, identify errors and correct simple bugs.
  • Create a basic class and object to represent a game.

2. Six-hour session timetable

09:00–09:20 - Mission briefing - Introduce the 6174 mystery and explain the challenge.

09:20–09:50 - Manual puzzle challenge - Students solve the puzzle using paper and pen.

09:50–10:20 - Algorithms and flow of logic - Translate the puzzle into human-readable steps.

10:20–10:35 - Break - 15 minutes, excluded from teaching time.

10:35–11:20 - Python fundamentals - Input, output, variables, data types and operators.

11:20–12:00 - Digit manipulation - Strings, sorting, subtraction and functions.

12:00–12:45 - Lunch - 45 minutes, excluded from teaching time.

12:45–13:30 - Conditions and loops - Teach decision-making and repetition.

13:30–13:45 - Break - 15 minutes, excluded from teaching time.

13:45–14:30 - Build the Kaprekar game - Combine the code into a working program.

14:30–15:00 - Classes, objects and assessment - Create a game object, debug and complete an individual challenge.

This timetable includes 360 minutes of teaching and 75 minutes of breaks plus lunch.

Session 1 — Mission briefing: What are we trying to solve? 20 minutes

Trainer script

“Today, you are not going to start by memorizing Python commands. You are going to solve a mystery.

I want each of you to choose a four-digit number. Arrange its digits from largest to smallest, then from smallest to largest. Subtract the smaller number from the larger number. Repeat the process.

Your mission is to discover what happens and then teach a computer to do it.”

Introduce the target number: 6174, known as Kaprekar's constant.

Do not explain the answer immediately. Let students investigate.

Session 2 — Solve the puzzle manually 30 minutes

Ask students to start with 3524.

Round

Descending

Ascending

Result

1

5432

2345

3087

2

8730

0378

8352

3

8532

2358

6174

4

7641

1467

6174

Trainer questions

  1. Which step did you repeat?
  2. Did the answer depend on the original number?
  3. Why did 6174 remain unchanged?
  4. Could a computer repeat these instructions hundreds of times?

Explain the special rule: use four digits throughout the rearrangement, including leading zeros. Starting numbers with four identical digits are excluded because they reach 0000 rather than 6174.

Students now have the problem that their first Python program will solve.

Session 3 — Understand algorithms and flowcharts 30 minutes

Before coding, explain that an algorithm is a sequence of steps used to solve a problem.

Write this algorithm on the board:

  1. Start.
  2. Get a four-digit number.
  3. Check that the number is valid.
  4. Arrange its digits in descending order.
  5. Arrange the same digits in ascending order.
  6. Subtract the smaller number from the larger number.
  7. Display the result.
  8. Repeat until the result becomes 6174.
  9. Stop and display the number of moves.

Trainer script

“A computer does not automatically know what we mean by a puzzle. We must break the puzzle into instructions that are precise enough for a computer to follow.”

Explain that a flowchart is a visual representation of these steps. Draw a simple flowchart on the board with Start, Input, Calculate, Decision, Repeat and End.

Ask students to identify which steps involve calculations and which steps involve decisions.

Session 4 — Python fundamentals: variables, data types and output 45 minutes

Start with the smallest possible Python program.

Step 1: Display a message

print("Welcome to the 6174 Mystery!")

print("Your mission is to find Kaprekar's constant.")

Explain that print() displays information on the screen.

Ask students to change the message to their own team name.

Step 2: Create variables


starting_number = 3524
current_number = 3524
moves = 0print("Starting number:", starting_number)
print("Current number:", current_number)
print("Moves completed:", moves)

Explain the three variables:

  • starting_number preserves the original number.
  • current_number stores the number currently being processed.
  • moves counts how many calculations have been performed.

A variable is a named reference to a value. Students can change the assigned value and observe the difference in output.

Step 3: Explore data types


number = 3524
digits = "3524"
moves = 0
game_over = False
print(type(number))
print(type(digits))
print(type(moves))
print(type(game_over))

Expected output:

<class 'int'>

<class 'str'>

<class 'int'>

<class 'bool'>

Explain these types in everyday language:

Type

Meaning

Example

int

Whole number

3524

str

Text

"3524"

float

Decimal number

3.5

bool

True or false

True

Step 4: Compare numbers and text


print(3524 + 1)

print("3524" + "1")

Output:

3525

35241

Explain that adding numbers performs arithmetic, while adding strings joins text together.

Practical task: Ask students to create their own team_name, score and current_number variables and display them.

Session 5 — Manipulate digits and write your first function

40 minutes

This is where students begin converting the puzzle into Python instructions.

Step 1: Convert the number into text

number = 3524

digits = str(number)

print(digits)

print(digits[0])

print(digits[1])

print(digits[2])

print(digits[3])

Explain that str(number) converts the integer to text. Each digit can now be accessed by its position, starting at index zero.

Step 2: Sort the digits

digits = "3524"

ascending_digits = sorted(digits)

descending_digits = sorted(digits, reverse=True)

print(ascending_digits)

print(descending_digits)

Output:

['2', '3', '4', '5']

['5', '4', '3', '2']

Explain that sorted() returns a list of individual characters in the requested order. Try input with different number, the print will be same response as the digits are printed as text.

Step 3: Join the digits



ascending = "".join(sorted(digits))

descending = "".join(sorted(digits, reverse=True))

print(ascending)
print(descending)

Output:

2345

5432

Explain that join() combines the characters into a single string.

Step 4: Convert the results back to integers and subtract

ascending_number = int(ascending)

descending_number = int(descending)

result = descending_number - ascending_number

print(result)

Output:

3087

Explain that int() converts a numeric string into an integer.

Step 5: Create a reusable function

def kaprekar_step(number):   
digits = f"{number:04d}"    

ascending = int("".join(sorted(digits)))   
descending = int("".join(sorted(digits, reverse=True)))   
result = descending - ascending    

return result
print(kaprekar_step(3524))
print(kaprekar_step(3087))


Expected output:

3087

8352

Explain the new concepts:

  • def defines a function.
  • number is the parameter.
  • return sends the calculated result back.
  • f"{number:04d}" formats the number as four digits, adding leading zeros where necessary.

Practical challenge: Ask students to calculate the next result from 3087 without manually writing a new set of instructions.

To calculate the next result from 3087, call the same function again with 3087 as the input.

Step 1: Understand the calculation

Arrange the digits of 3087 in descending and ascending order.

  • Descending: 8730

  • Ascending: 0378 (keep the leading zero when arranging the digits)

  • Subtract: 8730 - 378 = 8352

Therefore, the next result is 8352.

Step 2: Run this Python code



def kaprekar_step(number):
    digits = f"{number:04d}"

    ascending = int("".join(sorted(digits)))
    descending = int("".join(sorted(digits, reverse=True)))

    return descending - ascending

print(kaprekar_step(3524))
print(kaprekar_step(3087))
print(kaprekar_step(8352))

Output: 

Step 3: Let Python calculate the next result automatically

Instead of manually writing a new print() statement for each number, use a loop:


def kaprekar_step(number):
    digits = f"{number:04d}"
    ascending = int("".join(sorted(digits)))
    descending = int("".join(sorted(digits, reverse=True)))
    return descending - ascending

number = 3524

while number != 6174:
    number = kaprekar_step(number)
    print(number)

Syntax Error:



4 spaces for definition 

Session 6 — Teach conditions and loops

55 minutes

Students now know how to calculate one step. Next, they must teach the computer when to stop and when to repeat.

Step 1: Introduce conditions

number = 6174

if number == 6174:
    print("Mission completed!")
else:
    print("Keep trying!")



Explain that if checks a condition. The else branch runs when the condition is false.

Change number to 3087 and ask students to predict the output before running it.

Step 2: Introduce repetition

moves = 0

while moves < 3:
    moves += 1
    print("Move:", moves)



Explain that while repeats its instructions as long as its condition remains true. moves += 1 increases the counter by one.

Step 3: Combine the function and loop

number = 3524
moves = 0

while number != 6174:
    number = kaprekar_step(number)
    moves += 1


    print(f"Move {moves}: {number:04d}")

print("Total moves:", moves)


Expected output:



Move 1: 3087

Move 2: 8352

Move 3: 6174

Total moves: 3

Explain that the program repeatedly calls the function until the current number becomes 6174.

Debugging challenge: Ask students what would happen if they removed number = kaprekar_step(number) from the loop. They should discover that the number never changes and the loop never terminates.

Session 7 — Build the complete Kaprekar game 65 minutes

Now combine the concepts into one complete program.

Step 1: Add user input and validation


number = int(input("Enter a four-digit number: "))

if not 1000 <= number <= 9999:
    print("Invalid number. Enter a number from 1000 to 9999.")

elif len(set(str(number))) == 1:
    print("Choose a number with at least two different digits.")

else:
    print("Your number is valid!")

Explain:

  • input() accepts information from the user.
  • int() converts the input into an integer.
  • set() keeps only distinct digits.
  • len() counts how many distinct digits exist.
  • elif checks another condition when the preceding condition is false.

For a robust version, students should also handle non-numeric input using try and except, which will be taught in more detail later in the syllabus.

Step 2: Assemble the game

def kaprekar_step(number):
    digits = f"{number:04d}"

    descending = int("".join(sorted(digits, reverse=True)))
    ascending = int("".join(sorted(digits)))

    return descending - ascending


def play_kaprekar(number):

    if not 1000 <= number <= 9999:
        print("Please enter a four-digit number.")
        return

    if len(set(f"{number:04d}")) == 1:
        print("Choose a number with at least two different digits.")
        return

    moves = 0
    print("Starting number:", number)

    while number != 6174:
        number = kaprekar_step(number)
        moves += 1
        print(f"Move {moves}: {number:04d}")

    print("Congratulations! You reached 6174.")
    print("Total moves:", moves)

try:
    starting_number = int(input("Enter a four-digit number: "))
    play_kaprekar(starting_number)

except ValueError:
    print("Invalid input. Please enter digits only.")



Step 3: Test the game

Ask each student to test these cases.

Input

Expected behavior

3524

Reaches 6174 in 3 iterations

1234

Reaches 6174

2111

Reaches 6174

1111

Rejected because all digits are identical

123

Rejected because it is not four digits

abcd

Rejected with a helpful error message

Explain that testing different inputs helps us discover mistakes that may not appear in the first demonstration.

Step 4: Award mission points

Give each team points for:

  • Correctly explaining the algorithm.
  • Running the game successfully.
  • Handling an invalid input.
  • Fixing a deliberately introduced bug.
  • Reproducing the game independently.

The objective is understanding, not simply finishing first.

Session 8 — Introduce classes and objects

35 minutes

The syllabus introduces object-oriented programming in Day 1. Use the game students have just built to explain why classes and objects are useful.

Step 1: Explain using a simple analogy

Tell students:

“A class is like a blueprint for a game. An object is one actual game created from that blueprint. If four teams play the same game, each team can have its own game object with its own starting number and move count.”

Introduce these terms:

Term

Meaning in our game

Class

The blueprint for the game

Object

One instance of the game

Attribute

Starting number or move count

Method

An action such as play()

__init__()

Initializes a new game

self

Refers to the current game object

Step 2: Create the class

class KaprekarGame:
    def __init__(self, starting_number):
        self.starting_number = starting_number
        self.current_number = starting_number
        self.moves = 0

    def display_status(self):
        print("Starting number:", self.starting_number)
        print("Current number:", self.current_number)
        print("Moves:", self.moves)

game1 = KaprekarGame(3524)
game2 = KaprekarGame(1234)

game1.display_status()
game2.display_status()



Ask students why game1 and game2 have different starting numbers even though they use the same class.

Explain that each object stores its own attributes.

Step 3: Independent exercise

Ask each student to add a team_name attribute and a method called display_team().

They should be able to create two game objects with different team names and display them independently.

This is sufficient as an introduction to classes on Day 1. Inheritance, polymorphism, encapsulation and abstraction can be taught progressively on Day 2.

 

```html

Day 1 Knowledge Check

Python Programming Fundamentals | 5 Questions
Choose one answer for each question.

1. What is an algorithm?

2. What does a variable do?

3. Which keyword defines a function in Python?

4. Which construct repeats instructions while a condition is true?

5. What is the purpose of a class?

```

No comments:

Post a Comment