Zum Inhalt springen

English:Debugging Simple Programs

Aus MOOCsWiki Staging
Version vom 11. August 2026, 23:24 Uhr von Glanz (Diskussion | Beiträge) (aiMOOC über GPT aiMOOC Action erstellt)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)

Debugging Simple Programs



Introduction

A computer follows instructions exactly. That is useful, but it also means that a tiny mistake can make a program behave in a surprising way. When you find and fix mistakes in a program, you are debugging.

A mistake in a program is often called a bug. A bug might make a character move the wrong way, a game end too soon, a score change incorrectly, or a program stop with an error message. Debugging is not guessing until something works. It is a careful problem-solving process: decide what should happen, test the program, compare the result with your expectation, find the part that caused the problem, change it, and test again.

The photo above shows a famous real moth found in a relay of the Harvard Mark II computer in 1947. The word "bug" for a technical fault was already used before this event, so the moth did not invent the word. It became a memorable computer-history story because the operators had found an actual insect in the machine.

The Code.org story above introduces the idea of finding problems and working through them instead of giving up.

By the end of this aiMOOC, you should be able to explain what a bug is, describe a simple debugging cycle, test short programs, find common mistakes in sequences, loops, conditions, and variables, make one useful change at a time, and explain why your fix works.


What Is a Simple Program?

A program is a set of instructions that a computer can carry out. An algorithm is a clear plan or step-by-step method for solving a problem. When you turn an algorithm into instructions a computer can run, you create code.

You may write code with blocks in a tool such as Scratch, or you may type code in a language such as Python. Block coding and typed coding look different, but the same big ideas appear in both: sequence, repetition, choices, data, input, and output.

In Scratch, blocks fit together to form instructions. This helps prevent many spelling and punctuation mistakes, but a block program can still have logic bugs. For example, the blocks may be in the wrong order, a repeat count may be wrong, or a condition may test the wrong thing.

A simple square-making algorithm could be described like this:

repeat 4 times
    move forward
    turn right 90 degrees

The order matters. If you turn before moving, or repeat three times instead of four, the result changes. This is why debugging often begins by checking the sequence of instructions.


What Is a Bug?

A bug is a problem that makes a program behave differently from what was intended. To find a bug, you need two ideas:

Idea Question to ask
Expected result What should the program do?
Actual result What does the program really do?

The difference between the expected result and the actual result gives you a clue.

Suppose you expect a sprite to move 40 steps, but it moves 20 steps. That clue suggests checking the movement amount or the number of repetitions. If you expect a game to stop when the score reaches 10, but it continues at exactly 10, the condition may be using the wrong comparison.


Three Useful Bug Types

You do not need to memorize many difficult labels, but these three are useful:

Bug type What it means Simple example
Logic bug The program runs, but the plan or rule is wrong. A loop repeats five times when it should repeat four times.
Syntax bug Typed code does not follow the language rules. A word is misspelled or a required symbol is missing.
Runtime or setup bug The program starts but cannot complete an action because something it needs is missing or unsuitable. A program tries to use a file that is not available.

In block coding, logic bugs are especially common because the blocks may connect correctly even when the idea is wrong. In typed code, you may also see messages that point to syntax or runtime problems.


The Debugging Cycle

Good debugging is a cycle. You repeat it until the program matches the goal.

  1. Prediction: Say what you expect the program to do.
  2. Testing: Run the program with a clear test.
  3. Observation: Notice what actually happens.
  4. Locate the bug: Narrow the problem to a small part of the code.
  5. Editing: Change one useful thing.
  6. Retesting: Run the same test again.
  7. Explanation: Describe what was wrong and why the change fixed it.

The Code.org video above demonstrates an important idea: test a small part of the code so that you can find where the behavior first becomes wrong.

A strong debugger keeps evidence. Instead of saying, "It is broken," say something like, "I expected the sprite to turn after the third move, but it turns after the second move." That sentence tells you where to look.


Smart Debugging Strategies


Step Through the Program

Run or examine one instruction at a time. After each step, ask, "Is the program still doing what I expected?" The first step where the result becomes wrong is often close to the bug.

A step tool, when your coding environment has one, can make each instruction easier to observe.


Break a Big Problem Into Small Parts

If a program has twenty instructions, do not study all twenty at once. Test the first section, then the next. You can temporarily disconnect blocks or run a smaller function. This is sometimes called divide and test.


Change One Thing at a Time

If you change five things and the program suddenly works, you may not know which change solved the problem. One careful change makes the cause easier to understand.


Watch Important Values

Programs often store information in variables. A variable might hold a score, number of lives, timer value, or player name. If a result is wrong, watch how the variable changes.

For example:

score starts at 0
player catches a star
score changes by 1

If the score jumps from 0 to 2, look for a repeated score-change instruction or two events that both change the score.


Check Conditions Carefully

A condition is a yes-or-no test, such as "score is greater than 10" or "sprite is touching the edge."

These two conditions are not the same:

score > 10
score >= 10

If the game should end when the score reaches 10, the second condition fits that goal. Testing boundary values such as 9, 10, and 11 is a powerful way to check a condition.


Check the Starting State

Sometimes the code is correct, but the program starts with old information. A sprite may begin in the wrong place, a score may not reset, or a variable may still hold a value from the previous run.

Before a new test, make sure the program starts in a known state.


Read Error Messages

In typed programming, an error message is a clue. Read it slowly. It may show a line number, a name, or the kind of problem the computer noticed. The line named in the message is a place to investigate, but the true cause can sometimes be just before that line.


Debugging Block Programs

Block coding makes it easy to see the structure of a program. You can often debug by checking block order, loop size, conditions, events, and variable changes.

The Scratch image above shows a gravity and jumping script. Even when code looks neatly connected, you still need to test the behavior. A jump may be too high, gravity may be too strong, or the "touching ground" condition may not match the project.


Example: Wrong Loop Count

Goal: make a sprite draw a square.

repeat 3 times
    move 50 steps
    turn 90 degrees

The program can run, but it does not complete a square. The expected shape needs four equal sides and four turns. The bug is the repeat count.

A useful test is to count each side as it appears. After three sides, the result is still open. Changing the repeat count from 3 to 4 fixes the logic.


Example: Wrong Event

Imagine you want a sound to play when the green flag is clicked, but the sound only plays when a sprite is clicked. The sound block may be correct. The bug could be the event block at the top of the script.

This example teaches an important lesson: the place where you notice the problem is not always the place where the bug is located.


Example: A Loop That Never Stops

A forever loop is useful for actions that should continue for the whole program. It becomes a problem if you expected the program to stop after a certain number of actions.

Ask:

  1. Should this action repeat forever or a fixed number of times?
  2. Is there a condition that should stop the repetition?
  3. Does the program ever reach the code after the loop?


Debugging Typed Programs

Typed programming languages require you to follow writing rules as well as logic rules. Here is a small Python-style example:

name = "Sam"
print("Hello " + name)

If the variable is created as name but later typed as nmae, the program may report that the second name is unknown. The best fix is not to rewrite the whole program. Compare the variable names carefully.


Example: Wrong Comparison

Goal: print a message when the score is 10 or more.

score = 10

if score > 10:
    print("Level complete")

With a score of 10, the condition is false because 10 is not greater than 10. A better condition for the stated goal is:

if score >= 10:
    print("Level complete")

The code is short, but a good debugger still tests several values. Try 9, 10, and 11. The three results tell you more than testing only 10.


Example: Indentation

Some typed languages use indentation to show which instructions belong together.

if lives == 0:
    print("Game over")

If the second line is not placed where the language expects, the program may report an error or behave differently. When you see an indentation message, compare the spaces at the start of nearby lines.


Test Cases: Planned Experiments for Code

A test case is a planned input or situation with an expected result. Test cases help you check the program fairly instead of only trying random examples.

Suppose a game should give one point for each collected coin.

Test Starting score Coins collected Expected score
No coin 0 none 0
One coin 0 one 1
Several coins 2 three 5

If the program passes the first test but fails the third, you have learned something useful. The bug may only appear when an action happens more than once.

Good test cases include normal situations, edge cases, and simple cases that are easy to calculate by hand.


Debugging With a Flowchart

A flowchart shows steps and decisions using shapes and arrows. It can help you see the plan before looking at code.

Flowcharts often use different shapes for actions, decisions, input, and output. You do not need to memorize every symbol to use a flowchart for debugging. Follow the arrows and ask whether each choice leads to the correct next step.

The flowchart above was created as a code-checking example with issues to spot. Use it as a visual challenge: trace one path from start to finish, then ask where the logic could become confusing or incomplete.

A flowchart can help you separate an algorithm problem from a coding problem. If the flowchart already contains the wrong decision, copying it perfectly into code will still produce the wrong result.


Debugging With a Partner

Debugging can be a team activity. A helpful partner does not grab the keyboard and replace your work. A helpful partner asks questions that make the evidence clearer.

Useful partner questions include:

  1. What did you expect to happen?
  2. What actually happened?
  3. Which instruction ran just before the result became wrong?
  4. What is one small change we can test?
  5. What happened after the change?

You can also try rubber duck debugging: explain the program out loud to a toy, object, or partner, one instruction at a time. Speaking slowly can help you notice a missing step or a wrong assumption.


Common Mistakes and Useful Checks

What you notice A possible cause A useful first check
A sprite moves too far Movement amount or repeat count is too large Check the number in the move block and the loop
A score changes twice Two scripts may change the same variable Search for every place where the score changes
A game never ends The stop condition is never true Watch the condition and test the boundary value
A script never starts The wrong event triggers it Check the event block or starting command
Typed code reports an unknown name A variable or function name may be misspelled Compare the spelling where the name is created and used
The first run works but the second run does not Some state may not reset Reset variables, positions, or lists at the start

A table like this gives you starting ideas, not automatic answers. The same symptom can have several causes, so you still need evidence from tests.


Mini Debugging Lab

Try each problem before reading the explanation.


Lab A: The Turning Robot

Goal: a robot should move forward three times and then turn right.

Program:

move forward
move forward
turn right
move forward

Question: What is the smallest change that makes the program match the goal?

Check after trying: The third move should happen before the turn. Move the turn instruction to the end. This is a sequence bug.


Lab B: The Score Door

Goal: a door should open when the score reaches 5.

Program:

if score > 5
    open door

Question: Which test values would help you check the condition?

Check after trying: Test 4, 5, and 6. A score of 5 should open the door, so the condition needs to include 5, such as "score is greater than or equal to 5."


Lab C: The Double Score

Goal: collecting one gem should add one point.

You test the game once and the score changes from 0 to 2. You discover two different scripts that both run when the gem is collected, and both add 1.

Question: What evidence shows the likely cause?

Check after trying: One event causes two score-changing instructions. Remove or change the extra score update, then repeat the same one-gem test.


A Debugger's Checklist

Before you say that a program is finished, ask yourself:

  1. Can I state the expected result clearly?
  2. Did I test the program more than once?
  3. Did I test an edge case when a condition has a boundary?
  4. Did I watch important variables or states?
  5. Did I make one change at a time while debugging?
  6. Did I retest after every fix?
  7. Can I explain why the final version works?

Debugging is part of programming, not a sign that programming has failed. Programmers learn by making predictions, collecting evidence, changing code, and testing again.


Interactive Tasks


Quiz: Test Your Knowledge

What is debugging? (Finding and fixing problems in a program) (!Making a program longer) (!Changing every instruction at once) (!Running code without checking it)




What should you decide before comparing expected and actual results? (What the program should do) (!Which color the editor uses) (!How fast you can type) (!How many programs exist)




Why is changing one thing at a time useful? (It helps you know which change affected the result) (!It makes every program shorter) (!It removes the need for testing) (!It guarantees there are no bugs)




Which test best checks a condition that should become true at a score of 10? (Test scores 9 10 and 11) (!Test only score 50) (!Change the score randomly once) (!Skip the condition and continue)




A square program repeats its side instructions only three times. What kind of problem is this? (A logic bug) (!A missing computer) (!A network address) (!A file format)




What does a variable store? (Information that a program can use or change) (!Only pictures from the internet) (!A permanent computer password) (!Every instruction in the program)




What is a useful way to find where a long program first goes wrong? (Test smaller parts of the program) (!Rewrite the whole program immediately) (!Ignore the first wrong result) (!Add more code before testing)




What should you do after making a possible fix? (Run the test again) (!Delete the original goal) (!Stop observing the output) (!Change several more things first)




A script works once but starts with an old score the next time. What should you check first? (Whether the score resets at the start) (!Whether the monitor is bright) (!Whether the mouse has two buttons) (!Whether the code has comments)




What is a helpful debugging partner most likely to ask? (What did you expect to happen) (!Can I replace all your code) (!Why not guess a random fix) (!Can we skip the test)





Memory Game

Debugging Finding and fixing problems in a program
Algorithm A step by step plan for solving a problem
Variable A named place that stores information
Condition A test that can be true or false
Testcase A planned situation with an expected result
Sequence Instructions arranged in a meaningful order





Drag and Drop

Match the correct terms. Topic
Expected result What the program should do
Actual result What the program really does
Step through Check instructions one at a time
Retest Run the same check after a change
Reset state Put variables and objects back at their starting values




Compare your matches with the debugging cycle in the course.


Crossword Puzzle

Debugging What process finds and fixes problems in a program?
Variable What named place stores information that can change?
Algorithm What word means a clear step by step problem solving plan?
Condition What kind of test can be true or false?
Output What word describes information produced by a program?
Sequence What word describes instructions placed in a meaningful order?





LearningApps


Cloze Text

Complete the text.

Before you fix a program, decide what you

it to do. A difference between the expected result and the real result is evidence of a

. When you examine instructions one at a time, you are using a

strategy. A named place that stores changing information is a

. A true or false test in a program is a

. A planned check with an expected result is a

. After you change the code, you should

it. Good debuggers use observations and results as

.




Open-Ended Tasks


Easy

  1. Bug Diary: Keep a one-page diary of three small programming mistakes you meet, what you expected, what happened, and what fixed each one.
  2. Debugging Comic: Draw a four-panel comic in which a character finds a bug by testing one step at a time.
  3. Partner Interview: Interview a classmate about a time a program surprised them, then write a short summary of the clues they used.
  4. Sequence Repair: Create a six-step everyday algorithm such as making a sandwich, mix up two steps, and ask a partner to debug it.


Standard

  1. Scratch Bug Hunt: Build a short Scratch animation, add three planned logic bugs, swap projects with a partner, and record how each bug was found.
  2. Test Case Table: Choose a small game or calculator and design at least six test cases including normal cases and boundary cases.
  3. Debugging Tutorial Video: Record a two-minute screen or camera video showing one bug, the expected result, the actual result, one change, and the successful retest.
  4. Computer Lab Observation: Visit your school computer lab or makerspace with permission, observe how someone checks a technical problem, and compare that process with software debugging.


Advanced

  1. Variable Experiment: Build a program with a score or timer variable, deliberately create a wrong update, test several cases, and graph or tabulate the values you observe.
  2. Flowchart Investigation: Design a flowchart for a simple quiz or game, place one logic error in a copy, and write a challenge that asks another learner to locate it.
  3. Debugging Team Project: In a small group, create a program with loops, conditions, and variables, keep a shared bug log, and explain which evidence led to each fix.
  4. Compare Debugging Methods: Solve the same bug using two methods such as step through and divide and test, then write a reasoned comparison of which method was clearer and why.



Learning Assessment

  1. Explain a Fix: You are given a short program that should draw a square but repeats three times; explain the expected result, identify the logic bug, propose the smallest change, and justify it.
  2. Boundary Test Design: A game should unlock a level at 20 points; design three test values around the boundary and explain what each result would tell you.
  3. Trace and Diagnose: Trace a program that changes a score inside two different event scripts, predict the values after one event, and use the trace as evidence for a diagnosis.
  4. Compare Strategies: Compare changing one thing at a time with changing several things at once, and explain which approach gives stronger evidence about cause and effect.
  5. Transfer to Everyday Systems: Choose a non-computer process such as a classroom routine or recipe, identify an unexpected outcome, and show how the debugging cycle could help improve it.
  6. Reflect on Collaboration: Describe how a partner can help debug without taking control of the keyboard, and give two example questions that support the programmer's thinking.




Evidence of Learning

Your learning can be shown through more than a quiz score. Strong evidence includes what you know, what you can do, what you create, and how you transfer the idea of debugging to a new problem.

Type of evidence What successful learning can look like
Knowledge You can explain bug, debugging, algorithm, variable, condition, test case, expected result, and actual result in your own words.
Skills You can trace short code, isolate a faulty section, check a loop or condition, watch a variable, make one change, and retest.
Products You can produce a bug diary, test table, corrected program, flowchart, tutorial, or debugging report that records evidence.
Reasoning You can explain why a change fixes the problem instead of only saying that the new version works.
Collaboration You can ask useful questions, listen to another programmer's explanation, and help without taking over their work.
Transfer You can use the same predict, test, observe, change, and retest cycle in a new program or an everyday process.




OERs on the Topic

The English Wikipedia article below gives a broader introduction to debugging. Some parts are written for older learners, so use it to explore words and ideas you already know from this course.



Linked Learning Areas

Debugging connects programming with logical thinking, careful observation, mathematics, communication, and design. When you debug, you make a prediction, collect evidence, test cause and effect, and explain your reasoning.


aiMOOC Projects