Thursday, 15 October 2026

Teaching Python from Scratch: A Foundation-First Approach

Let's start with how to read, write, and understand Python programs before we design games or use advanced concepts such as OOP, decorators, and generators.

Understand the instruction → Predict the result → Write the code → Run it → Observe the result → Modify it.


1. What is the very first line of Python code?

The traditional first program is:

print("Hello, World!")




Output:


Hello, World!


























Python does not require every program to begin with print(). It is simply an easy first example because students can immediately see a result.


2. How many different ways can a Python program begin?

There is no fixed number of opening lines in Python. A program begins with whatever instruction is appropriate for its purpose. However, beginners can learn a small set of common patterns.

Here are 12 useful starting patterns to teach progressively.

3. Twelve common Python starting patterns

Teach these as patterns, not as 12 rules students must memorize on day one.

1. Display a message
Print("Welcome to Compass Clock Consultancy")




Use: Display text, instructions, and results.

2. Store a value

name = "Thameem Ansari" print(name)






Use: Store and reuse information. Here, name is a variable.



3. Ask the user for input

name = input("Enter your name: ") print("Welcome", name)







Use: Make a program interactive. input() returns text.

4. Perform a calculation

a = 10 b = 5 print(a + b)











Use: Arithmetic and numeric calculations. Task: Now, try Sub, Multi & Division these are also called as operators.


5. Make a decision

score = 75 if score >= 50: print("Pass") else: print("Try again")












Use: Run different instructions based on a condition. Task: Now modify the code to ask the user to input the score.

6. Repeat an action








for number in range(1, 4): print(number)

Use: Repeat an instruction. Output: 1, 2, 3.

Task: Now get an output:1,2,3,4.

Easy rule to remember

range(start, stop) includes the start but excludes the stop.

Code

Output

range(3, 10)

3 to 9

range(3, 11)

3 to 10

range(1, 6)

1 to 5

range(1, 11)

1 to 10

Classroom tip: Add 1 to the final number if you want to print when using range() with two arguments.

7. Create a list

games = ["Vault", "Quiz", "Robot"]
print(games)



Use: Store multiple items in one variable.

8. Define a function

def greet():    print("Welcome!")greet()



Use: Create a reusable block of instructions.

Understanding Python Functions with Simple Illustrations

Your example is one of the best starting points for teaching functions to beginners.

def greet():    print("Welcome!")greet()

The key idea is: a function is a reusable set of instructions. You define it once and call it whenever you want to execute it.

8.1. Illustration: A function is like a machine


You write the instructions

def greet():

GREETING MACHINE

print("Welcome!")

The instruction is stored, ready to be used.

You call the function

greet()

Output: Welcome!


Tip: writing a recipe is not the same as cooking the food. Similarly, defining a function does not execute its instructions. Calling it does.

8.2. Understand each line

def

Define

Tells Python that you are defining a function.

greet

Function name

The name you choose for this reusable instruction.

()

Parentheses

Hold the parameters the function may need. This function has none.

:

Colon

Marks the beginning of the function's body.

Indentation

Function body

The indented print() line belongs to the function.


8.3. Illustration: Define first, call later





def greet():
print("Welcome!")

print("Program starts")
greet()
print("Program ends")

Output:

Program starts
Welcome!
Program ends




Follow the arrows to understand the order:


1. Start program

2. Define greet()

Python stores the function instructions; it does not print Welcome yet.

3. Print "Program starts"

4. Execute greet()

Welcome!

5. Print "Program ends"

Think: What happens if we remove greet()?

Answer: The program will not display Welcome!, because the function was defined but never called.

8.4. Illustration: Call the same function multiple times

You don't need to write the same instruction repeatedly.


def greet():
print("Welcome!")
greet()
greet()
greet()

Output:

Welcome!
Welcome!
Welcome!

One function, three calls

Call 1 Welcome!

Call 2 Welcome!

Call 3 Welcome!


This is the main benefit of functions: code reusability.

8.5. Illustration: Give information to a function

Now let's make the greeting more useful. Suppose you want to greet different students.














def greet(name):
print("Welcome", name)

greet("Kavitha")
greet("Rahul")
greet("Aisha")

Output:

Welcome Kavitha
Welcome Rahul
Welcome Aisha

How does it work?

Function definition def greet(name):

greet("Kavitha")

name = Kavitha

greet("Rahul")

name = Rahul

greet("Aisha")

name = Aisha

Here, name is called a parameter. "Kavitha", "Rahul", and "Aisha" are arguments supplied when the function is called.

8.6. Illustration: A function that calculates something

Functions can do more than display messages.

def add(a, b):
result = a + b
print(result)

add(10, 5)
add(20, 30)

Output:

15
50


The function receives two values, adds them, and displays the result.

A slightly more advanced version uses return:

def add(a, b):
return a + b

answer = add(10, 5)
print(answer)

Output:

15


What Happens:

  • print() displays information.

  • return sends a value back to the place where the function was called.

For example, return allows the result to be stored in answer and used in another calculation.

8.7. Illustration: Functions inside your Game Factory

How to use this in our Game factory.

def show_instructions():
print("Welcome to Vault Breaker!")
print("Guess the secret number.")
print("You have three attempts.")

def start_game():
show_instructions()
print("Game starting...")

start_game()

Output:

Welcome to Vault Breaker!
Guess the secret number.
You have three attempts.
Game starting...

Notice that one function can call another function. This helps programmers divide a large program into smaller, understandable tasks.

8.8. Lets experiment

Exercise 1: What is the output?

def greet(): print('Hello') greet()

Exercise 2: How many times is Welcome printed?

def greet(): print('Welcome') greet() greet()

Exercise 3: What is the output?

def greet(name): print('Hi', name) greet('Thameem Ansari')


8.9. The key points students should remember

  1. def defines a function.

  2. A function name identifies the reusable block of code.

  3. The indented statements form the function body.

  4. Defining a function does not execute it.

  5. Calling the function with greet() executes it.

  6. Parameters allow functions to receive information.

  7. return sends a result back to the caller.

Classroom activity: Ask every student to create a function called introduce() that prints their

name, course, and one skill they want to learn. Then ask them to call the function twice.

This reinforces function definition, execution, and reusability before moving to classes and objects.

9. Handle an error

try:
number = int("25")
print(number)except ValueError:
print("Invalid number")

Use: Handle expected errors safely.



Python try and except —Explained from Scratch

How to handle errors without allowing a program to crash unexpectedly.


try:
    number = int("25")
    print(number)
except ValueError:
    print("Invalid number")

Let's understand it line by line, using simple examples

9.1. First, understand what happens without try and except

Consider this program:


number = int("hello")print(number)

Python produces an error similar to:

ValueError: invalid literal for int() with base 10: 'hello'

Why?

  • int() converts suitable text into an integer.
  • "hello" contains letters, not a valid integer representation.
  • Python cannot perform the conversion, so it raises a ValueError.
  • The program stops before print(number) executes.

Think of int() as a machine that converts text into whole numbers.

If you give it "25", it works. If you give it "hello", it cannot complete the conversion.

9.2. What do try and except mean?



try
Attempt to execute the code

Python runs the statements inside the try block. If a matching error occurs, it looks for an appropriate except block.

except
Handle a particular error
If the specified error occurs in the try block, Python executes the matching handler instead of displaying the unhandled traceback.

The structure is:


try:
    # Code that might cause an error
    pass


except ValueError:
    # What to do if a ValueError occurs
    print("Please check your input")

The pass is simply a placeholder here. Replace it with your actual program instructions.

9.3. The original example, explained line by line

try:
    number = int("25")
    print(number)
except ValueError:
    print("Invalid number")

Line

Meaning

try:

Start the block that may raise an error.

number = int("25")

Convert the text "25" into the integer 25.

print(number)

Display the converted number.

except ValueError:

Specify what to do if a ValueError occurs in the try block.

print("Invalid number")

Display a friendly message if that error occurs.

Output:

25

The conversion succeeds, so the except block is skipped.

Important: The except block does not run every time. It runs only when a matching exception occurs in the try block.

9.4. Compare three different examples

Example A — Valid number


try:
    number =int("25")        print(number)
except ValueError:        print("Invalid number")

Output: 25

Why? "25" can be converted into an integer, so no ValueError occurs.

Example B — Invalid text



try:    number = int("hello")    print(number)except ValueError:    print("Invalid number")

Output: Invalid number

Why? "hello" cannot be converted into an integer. Python jumps to the matching except block. print(number) inside try is not executed.

Example C — Negative number


try:
    number =int("-10")        print(number)
except ValueError:        print("Invalid number")

Output: -10

Why? A negative integer is valid. int("-10") succeeds, although a particular game might have

separate rules forbidding negative numbers.

9.5. Use input() to make it interactive

Now let's apply the concept to a student's actual program.

try:
    number =int(input("Enter a whole number: "))
    print("You entered:",number)
except ValueError:
    print("Invalid input! Please enter a whole number.")

Possible outcomes:

42 Valid input

Output: You entered: 42


hello Invalid input

Output: Invalid input! Please enter a whole number.


12.5 Not a whole number

The conversion with int() raises ValueError. Use float() if decimal values are allowed.


Notice the difference between int("25") and input("Enter a number: "). The first receives text

that is already rovided in the code; the second asks the user to supply text while the program is running.

9.6. Example: Validate a student's score

Suppose students must enter a score between 0 and 100.

try:
    score =int(input("Enter your score: "))   

    if score < 0 or score > 100:                print("Score must be between 0 and 100.")
    elif score >= 50:
        print("Pass")
    else:                print("Try again")
except ValueError:
    print("Please enter a whole number.")


Try these inputs:

Input

Result

75

Pass

45

Try again

0

Try again

100

Pass

120

Score must be between 0 and 100.

hello

Please enter a whole number.

Here, two different mechanisms are at work:

  • try/except handles an input that cannot be converted to an integer.
  • if/elif/else handles valid integers according to the program's rules.

For example, 120 is a valid integer, but it is an invalid score under these rules.

That is a validation problem, not a conversion error.

9.7. What if we want the user to try again instead of stopping?

This is useful for your Game Factory exercises.

while True:        try:
        number =int(input("Enter a whole number: "))
        print("Accepted:",number)
        break

    except ValueError:
        print("Invalid input. Try again.")

How it works:

  1. while True repeats the process.
  2. try attempts the conversion.

  3. If conversion fails, except displays a message.
  4. The loop starts again because break was not executed.
  5. If conversion succeeds, break exits the loop.

The user can therefore correct the input without restarting the program.

9.8. Common errors to teach students

Mistake

Why it is a problem

Forgetting the colon after try:

Python syntax error

Forgetting indentation

Python cannot identify the block correctly

Writing except: for every error

It may hide errors the programmer did not intend to handle

Putting print(number) before the conversion

The variable may not yet exist

Assuming every invalid value raises an exception

Values such as 120 need explicit rule checks if they are outside the permitted range

Prefer handling the specific exception you expect, such as ValueError, rather than catching every possible exception indiscriminately.

9.9. Student practice

1. What is the output if `int('25')` succeeds?

25

Invalid number

ValueError

2. What happens when `int('hello')` is executed?

It returns 0

It raises ValueError

It returns the word hello


3. If the user enters 120 as a score, is it a ValueError?

Yes, always

No, it is an integer; range rules must reject it

Python automatically changes it to 100

4. What does `break` do in the retry example?

Restarts the whole program

Exits the loop

Handles ValueError


The main lesson

Remember this simple formula:

try = attempt the operation.

except = handle the expected error.

if/else = make a decision based on a condition.

while = repeat an action when needed.

Together, these concepts help students build Python programs that are interactive, robust, and easier to use.

10. Import a library


import mathprint(math.sqrt(25))

Use: Access existing Python functionality. Output: 5.0.

 

11. Work with data


import numpy as np

numbers = np.array([10, 20, 30])
print(numbers.mean())



Use: Begin numerical and AI-related data work. NumPy must be installed in the Python environment.

12. Define a class



class Game:
def __init__(self, name):
self.name = name

game = Game("Vault Breaker")
print(game.name)




Use: Introduce Object-Oriented Programming after students understand variables, functions, and indentation.

Remember the terms

01 Read and display

print(), strings, numbers, comments, quotation marks.

Exercise: Display the student's name, course name, and game title.

02 Store and receive information

Variables, data types, input(), type conversion.

Exercise: Ask for a player's name and age, then display them.

03 Calculate and compare

Arithmetic operators, comparison operators, Boolean values.

Exercise: Calculate a game score and determine whether it meets a target.

04 Make decisions

if, elif, else, indentation, logical operators.

Exercise: Display “Correct”, “Too high”, or “Too low”.

05 Repeat and organize

for, while, lists, indexing, break, continue.

Exercise: Give the player three guesses at a secret number.

06 Create reusable code

Functions, parameters, arguments, return, scope.

Exercise: Create a function that checks a guess or calculates a score.

07 Build reliable programs

Exceptions, defensive programming, debugging, testing.

Exercise: Handle letters entered where a number is expected.

08 OOP

Classes, objects, __init__(), self, inheritance, overriding, polymorphism.

Exercise: Turn the number guessing game into a Game class and create a second game.

09 Extend and improve

Decorators, generators, abstraction, encapsulation.

Exercise: Monitor game sessions and supply missions one at a time.

10 Prepare for AI data work

NumPy arrays, Pandas DataFrames, cleaning, analysis, visualization.

Exercise: Store game scores in a table, clean the data, and calculate results.

 


































No comments:

Post a Comment