Your First Program, Variables, Loops and Conditions

Lesson by Adnan, computer science lecturer  ·  aitrendblend editorial team  ·  Computer Science Education  ·  October 2026  ·  Reading time about 22 minutes

Programming Variables Loops Conditions Debugging Python Grades 9 to 12
Your First Program: Animated beginner programming lesson illustration with a small robot following code blocks across a grid to a star
Your First Program
Variables, Loops and Conditions
Every app, game and website is built from three simple ideas. Students meet all three here, first with a robot and then in real Python.
On the first day of a programming course, a student types a line, presses run, and the screen fills with red error text. For many people that moment decides whether they think programming is for them. It should not. Programs are built from just three ideas, boxes that remember values, decisions that choose what happens next, and loops that repeat work, and each one can be understood before anyone touches a keyboard. In this lesson students watch variables change line by line, program a little robot across three levels, trace real Python code step by step and hunt down bugs planted in short programs. By the end, error messages stop looking like failure and start looking like clues.

Key points of this lesson

  • A program is a precise list of instructions, and a computer follows it exactly, including any mistakes.
  • A variable is a named box that holds a value, and the equals sign in code means store, not equals.
  • Conditions such as if and else let a program make decisions based on data.
  • Loops repeat work, and finding the repeating pattern makes programs shorter and clearer.
  • Bugs are normal. Tracing a program line by line is the most reliable way to find them.
  • Five live labs, a quiz and runnable Python code take students from robot commands to real code.

Who this lesson is for and how to use it

This is the eighth lesson in our Computer Science Education series, and it is the one that turns ideas into practice. Earlier lessons explained how a computer runs instructions, in How a Computer Works, and described famous algorithms such as sorting, searching and graph search. Here students write instructions of their own. Teachers can also use this lesson first, as an introduction to programming, before the more theoretical lessons in the series.

The lesson suits grades nine to twelve and complete beginners of any age. The robot lab needs no typing at all, which makes it a gentle start for students who have never programmed. The code tracer and bug hunt use real Python, the language used in most school courses and in the companion code for every lesson in this series.

Learning objectives

After three periods, a student should be able to do the following five things without notes.

  1. Explain what a variable is and predict its value after a sequence of assignments.
  2. Write a short sequence of commands, and shorten it using a loop.
  3. Read an if and else statement and say which branch runs for a given value.
  4. Trace a for loop and a while loop by hand, writing down each variable as it changes.
  5. Find and fix a simple bug by tracing, and explain what caused it.
PeriodFocusActivity on this pageTime
1Instructions and variablesThe human robot game, Lab 1 variable boxes, Lab 2 robot level 140 minutes
2Loops and patternsLab 2 robot levels 2 and 3, Lab 3 code tracer40 minutes
3Conditions and debuggingLab 3 even and odd, Lab 4 bug hunt, quiz, Python demo40 minutes

What a program really is

A program is a list of instructions written precisely enough for a machine to follow. Students already know the idea from the first lesson in this series, where the toy CPU fetched one instruction at a time and executed it. The difference now is that people do not write LOAD and ADD by hand. They write in a programming language such as Python, and a program called an interpreter translates each line into the simple steps the CPU understands.

The most important fact about computers is also the most surprising to beginners. A computer does exactly what you tell it, not what you meant. If you tell a robot to walk forward three steps and the door is four steps away, it will stop one step short every single time. That is not stubbornness. It is the reason computers are useful. A machine that guessed what you meant would be impossible to rely on.

The idea is older than electronic computers. In 1843 Ada Lovelace published notes on Charles Babbage’s planned Analytical Engine, including a step by step method for calculating a sequence of numbers called Bernoulli numbers. Many historians call it the first published computer program, written for a machine that was never finished.

Code blocks guiding a robot to a star On the left, lines of a short program appear one after another. On the right, a small robot moves along a grid path, turning at corners, until it reaches a star. repeat 3 times: forward turn right repeat 2 times: forward # robot reaches the star
Figure 1. A program is a recipe for a machine. Two repeat blocks and a turn are enough to guide the robot to the star, and the robot will follow them exactly, every time.

Teacher note, the human robot

Ask one student to be a robot who only understands three commands, forward one step, turn left and turn right. The class must guide the robot from the door to a chair using only those commands, written on the board first and read out afterwards. The robot follows them exactly, bumping into a desk if the class miscounts. Students discover precision, sequence and debugging in ten minutes, before they see a single line of code.

Variables, boxes with names

A program needs somewhere to remember things, a score, a name, how many lives are left. It stores them in variables. A good picture is a labelled box. The label is the variable’s name and the contents are its value. Writing score = 5 in Python puts the number 5 into a box labelled score.

That equals sign causes more confusion than anything else in a first programming course, because it does not mean what it means in maths. In code it means take whatever is on the right, work it out, and store the result in the box on the left. That is why a line like score = score + 1 makes perfect sense to a computer even though it would be impossible as an equation. Step through the program below and watch the boxes change.

Lab 1. Variables are boxesone line at a time

Memory

Before you press Step, predict the final values of score and bonus. Then check.

Two lessons hide in this lab. Line three uses the old value of score before replacing it, which is exactly how the accumulator in our toy CPU worked. And changing score on line three does not change bonus, because bonus already holds its own copy of the number 8. Boxes are independent unless a line of code connects them.

Sequence and loops, teaching a robot

The simplest programs are sequences, one instruction after another. Sequences get long fast. Moving a robot five squares means writing forward five times, and a real program might need to do something a million times. Loops solve this. A loop says repeat these instructions a number of times, or keep repeating while something is true. Spotting the repeating pattern in a task, and wrapping it in a loop, is one of the core skills of programming.

The robot below understands four blocks, forward, turn left, turn right and repeat. Build a program by clicking blocks, then press Run. Each level shows the length of the shortest program. Try solving each level the long way first, then find the pattern and use a repeat block to match the shortest.

Lab 2. Program the robotthree levels
times
0blocks used
2shortest possible

Level 3 is the one that makes students think. The staircase looks complicated, but it is just the same four moves over and over, forward, turn right, forward, turn left. One repeat block holding those four moves solves it in five blocks. Recognizing that a big problem is a small pattern repeated is called decomposition, and it is how programmers tackle everything from games to operating systems.

The robot has an ancestor. In 1967 Seymour Papert and his colleagues created a language called Logo, in which children programmed a turtle, at first a real robot on the floor and later a triangle on the screen. Block based languages such as Scratch, released by the MIT Media Lab in 2007, grew from the same idea, and students who enjoy this lab will find Scratch an excellent next step.

Key takeaway

A loop turns a long program into a short one by describing the pattern once. Finding the pattern is the real work, and it is a skill that improves with every puzzle.

Conditions, programs that decide

A program that always does the same thing is not very useful. Games react to key presses, calculators react to the numbers typed in, and a grading system gives different results for different marks. All of these use conditions. An if statement checks whether something is true and runs a block of code only when it is. An else block runs when it is not. Comparison symbols do the checking, == for equal, != for not equal, and the familiar greater than and less than signs.

if marks >= 40:
    print("Pass")
else:
    print("Fail")

In Python the lines inside an if, an else or a loop are indented by four spaces. The indentation is not decoration. It tells Python exactly which lines belong to which block, and getting it wrong is one of the first errors every beginner meets.

Tracing code line by line

Professional programmers rarely understand a program by staring at it. They trace it, following the computer’s path one line at a time and writing down every variable as it changes. The tracer below does that automatically for three short Python programs. Press Step and watch which line runs, how the variables change and what gets printed. Then try predicting the next line before pressing Step again.

Lab 3. Code tracerreal Python, one step at a time

Variables

Output

step 0

Notice two things that trip up almost every beginner. In the first program range(1, 6) stops at 5, not 6, because Python ranges leave out their end number. In the times table program the while loop only stops because line four increases i. Remove that line in your head and the condition i <= 5 would stay true forever. The tracer makes both facts visible, which is exactly why tracing is the most powerful debugging tool a beginner has.

An error message is not the computer telling you that you failed. It is the computer telling you where to look.From this lesson, period three

Debugging, finding what went wrong

Every programmer writes bugs, including the best in the world. The word has a famous story. In September 1947 engineers working on the Harvard Mark II computer found a real moth trapped in a relay and taped it into their logbook with the note first actual case of bug being found. Grace Hopper, who worked on that machine and later created one of the first compilers, liked to tell the story, and the word stuck.

Most bugs fall into a few familiar types. A logic error does the wrong calculation, such as overwriting a total instead of adding to it. An off by one error uses the wrong boundary, such as greater than where greater than or equal was needed. An infinite loop never meets its stopping condition. Each program below contains one bug. Read the task, trace the code in your head and click the line you think is wrong.

Lab 4. Find the bug0 found

Teacher note, normalizing errors

Keep a class bug wall. Every time a student meets an error, they write the message and the fix on a sticky note and add it to the wall. Within a week the class has its own reference guide, and students see that everyone, including the teacher, makes mistakes. This one habit does more for beginner confidence than any amount of explanation.

Key takeaway

Debugging is a skill, not a sign of failure. Read the error, trace the code line by line, check what each variable really holds, and the bug almost always reveals itself.

Timeline of programming milestones Seven milestones appear in turn, from Ada Lovelace’s program in 1843 to Scratch in 2007. 1843Lovelace’sprogram 1947the firstreal bug 1952Hopper’scompiler 1957FORTRANreleased 1967Logo andthe turtle 1991Pythonfirst release 2007Scratchfor schools
Figure 2. From a program for a machine that was never built to block languages designed for children. Each step made programming easier for more people.

A short history of making programming easier

The story of programming languages is a story of making computers easier to instruct. The first electronic computers were programmed by setting switches and plugging cables. In 1952 Grace Hopper built the A-0 system, an early compiler that translated instructions into machine code, against colleagues who believed computers could only do arithmetic. In 1957 a team at IBM led by John Backus released FORTRAN, which let scientists write formulas almost the way they wrote them on paper.

Python was first released in 1991 by the Dutch programmer Guido van Rossum, who wanted a language that was pleasant to read. Its clean, indented style is why so many schools teach it first, and why it dominates AI research today, including every PyTorch model on this site. Our guide to the open source machine learning frameworks used in 2026 shows how far a beginner’s Python can eventually reach, and our article on AI coding assistants explains why understanding code yourself still matters even when a chatbot can write it.

Misconceptions students bring to class

  • The equals sign means equals. In code it means store. The right side is worked out first, then saved in the variable on the left.
  • The computer will understand what I meant. It follows exactly what you wrote. Precision is the whole point.
  • Good programmers do not make errors. Every programmer writes bugs. Good programmers are good at finding them.
  • You must memorize a language before you can program. Programming is mostly thinking in steps, patterns and decisions. The syntax comes with practice, and documentation is always there.
  • AI can write code now, so learning is pointless. AI tools produce code that still needs to be read, checked and fixed, which requires exactly the skills in this lesson.

Where this lesson simplifies the truth

The robot language has only four commands and no variables or conditions, while real languages have hundreds of features. The code tracer shows a simplified view of execution, and real Python creates and updates variables in ways that matter later, for example when two names refer to the same list. The bug hunt uses short, tidy programs, while real bugs often hide across many files and only appear with unusual input.

Python’s indentation rules, data types such as strings and lists, and functions are only touched on here. Each deserves a lesson of its own. The goal of this lesson is the mental model underneath them all, boxes, decisions, repetition and careful tracing, which transfers to every language students will ever learn.

Bringing it all together

The main achievement of this lesson is confidence. Students have watched variables change one line at a time, guided a robot with sequences and loops, traced real Python through loops and conditions, and hunted down three classic bugs. None of it required memorizing anything. It required thinking precisely, step by step, which is what programming really is.

The conceptual shift is from seeing code as a mysterious text written by experts to seeing it as a list of instructions anyone can read, trace and fix. Once students can predict what each line does, they can understand any program, however long, by breaking it into lines they understand.

The ideas connect every lesson in the series. Variables live in the RAM from How a Computer Works. Loops and conditions are how sorting, searching and graph algorithms are written. The training loop from How AI Learns is literally a loop that repeats until the error is small, and the companion code for every lesson uses only the ideas taught here, plus a few functions.

The lesson has honest limits. It does not cover functions, lists, strings or input in depth, and the robot world is far simpler than real programs. Teachers with stronger classes can extend period three by asking students to modify the companion code, for example adding a grade for marks above 90, and teachers without computers can run the entire unit with the human robot game, paper code tracing and a bug hunt on the board.

A natural next lesson is functions, packaging a useful piece of code under a name so it can be reused. For now, the student who saw a screen full of red text on day one can read that text calmly, find the line it points to, and fix it.

Companion Python code for the classroom

The program below uses every idea from the lesson. It shows variables changing, uses if, elif and else to turn marks into grades, loops through a class list to compute an average and count each grade, and simulates the same robot as Lab 2, including repeat blocks and a deliberate bump into a wall that raises an error.

pg_lesson_code.py  ·  Python 3  ·  no extra libraries
# Your First Program, companion code for the aitrendblend lesson
# Runs on any Python 3 installation. No extra libraries needed.

# Part 1. Variables are named boxes
score = 5
bonus = score + 3        # bonus is 8, score is still 5
score = score * 2        # read the old value, then store the new one
print("score:", score, "bonus:", bonus)

# Part 2. Conditions make decisions
def grade(marks):
    if marks >= 80:
        return "A"
    elif marks >= 60:
        return "B"
    elif marks >= 40:
        return "C"
    else:
        return "Fail"

# Part 3. Loops repeat work
def class_report(marks_list):
    total = 0
    counts = {}
    for m in marks_list:                 # once for every student
        total = total + m
        g = grade(m)
        counts[g] = counts.get(g, 0) + 1
    average = total / len(marks_list)
    return round(average, 1), counts

# Part 4. A tiny robot, the same rules as Lab 2
DIRS = [(0, -1), (1, 0), (0, 1), (-1, 0)]   # north, east, south, west


def run_robot(program, start=(0, 0), facing=1, walls=(), size=5):
    x, y, d = start[0], start[1], facing
    path = [(x, y)]

    def step(cmd):
        nonlocal x, y, d
        if cmd == "F":
            nx, ny = x + DIRS[d][0], y + DIRS[d][1]
            if 0 <= nx < size and 0 <= ny < size and (nx, ny) not in walls:
                x, y = nx, ny
                path.append((x, y))
            else:
                raise RuntimeError(f"Bump! wall ahead at {(nx, ny)}")
        elif cmd == "L":
            d = (d - 1) % 4
        elif cmd == "R":
            d = (d + 1) % 4

    for item in program:
        if isinstance(item, tuple):      # ("repeat", n, [commands])
            _, n, body = item
            for _ in range(n):
                for cmd in body:
                    step(cmd)
        else:
            step(item)
    return (x, y), path


# Smoke test
if __name__ == "__main__":
    marks = [91, 74, 38, 66, 55, 82, 47]
    avg, counts = class_report(marks)
    print("Class average:", avg, "grades:", counts)

    # Level 1 of the robot lab: go 4 east, turn right, go 4 south
    long_way = ["F", "F", "F", "F", "R", "F", "F", "F", "F"]
    with_loops = [("repeat", 4, ["F"]), "R", ("repeat", 4, ["F"])]
    end1, _ = run_robot(long_way)
    end2, path = run_robot(with_loops)
    print("Robot ends at", end2, "after", len(path) - 1, "moves, program length", len(with_loops))

    try:
        run_robot(["F", "F"], walls={(2, 0)})
    except RuntimeError as e:
        print("Bug found:", e)

    assert score == 10 and bonus == 8
    assert grade(80) == "A" and grade(39) == "Fail"
    assert counts == {"A": 2, "B": 2, "C": 2, "Fail": 1}
    assert end1 == end2 == (4, 4)
    print("\nAll checks passed.")

When you run it, score should be 10 and bonus 8, the class average should be 64.7 with two of each grade from A to C and one fail, the robot should reach the corner using a three item program, the wall bump should be reported as a bug, and the final line should report that all checks passed. A good extension task is to add a new grade for marks of 90 or more, then add a robot level with walls and write the shortest program that solves it.

Check your understanding

Six questions cover the whole lesson. Choose an answer for each and press Check answers to see which were right, with a short explanation for each.

Lab 5. Quick quizsix questions

Frequently asked questions

What is a variable in programming?

A variable is a named place in memory that holds a value, such as a number or a word. It works like a labelled box. Assigning a new value replaces what was in the box.

What is the difference between a for loop and a while loop?

A for loop repeats once for each item in a sequence, such as the numbers from 1 to 5. A while loop repeats as long as a condition stays true, so something inside it must eventually make the condition false.

What does an if statement do?

An if statement checks a condition and runs a block of code only when the condition is true. An else block can run a different block when it is false, so the program can make decisions.

Why is Python a good first programming language?

Python is readable, uses indentation to show structure clearly, and is widely used in schools, science and artificial intelligence, so the skills students learn stay useful for a long time.

How do beginners find bugs in their code?

The most reliable method is tracing, following the program one line at a time and writing down each variable as it changes, then comparing what actually happens with what should happen.

Can programming be taught without computers?

Yes. Students can act as robots following written commands, trace code on paper, and hunt bugs in programs written on the board. These activities build the thinking that programming needs.

Take the lesson further

Continue with block programming in Scratch, then move on to writing real Python with the official tutorial.

Scratch by MIT Official Python tutorial

Sources. Ada Lovelace, notes on L. F. Menabrea’s Sketch of the Analytical Engine, Scientific Memoirs, 1843. Harvard Mark II logbook entry, 9 September 1947, held by the Smithsonian National Museum of American History. Grace Hopper, The Education of a Computer, Proceedings of the ACM, 1952. John Backus and colleagues, The FORTRAN Automatic Coding System, 1957. Seymour Papert, Mindstorms, Children, Computers and Powerful Ideas, Basic Books, 1980, describing Logo. Mitchel Resnick and colleagues, Scratch, Programming for All, Communications of the ACM, 2009. Python Software Foundation, History of Python.

This lesson is based on standard introductory programming teaching material and the classroom experience of the author. The robot and code tracer are simplified teaching models.

Related reading on aitrendblend

Leave a Comment

Your email address will not be published. Required fields are marked *