English:Conditional Logic and Loops

Conditional Logic and Loops
Introduction
Conditional Logic and Loops is a Grades 9–10 course about two core ideas in programming: making decisions and repeating actions. Together, these ideas control the order in which instructions run. This order is called control flow.
You use conditional logic when a program must choose between actions. You use loops when a program must repeat an action, process several items, or continue until a condition changes. These ideas appear in games, apps, robotics, websites, data analysis, simulations, and many everyday algorithms.
A flowchart can make control flow visible. Arrows show the path of execution, while decision shapes show where the path can change.

By the end of this aiMOOC, you should be able to read, trace, design, explain, and debug programs that use conditions and loops. The examples use clear Python-like syntax, but the main ideas apply to many programming languages.
Learning Goals
After working through the course, you can:
- Control flow: Explain how a program moves through a sequence of instructions, decisions, and repeated blocks.
- Conditional statements: Use conditions to choose between alternative actions.
- Boolean logic: Combine comparisons with AND, OR, and NOT.
- Loops: Choose and use for loops and while loops for suitable problems.
- Debugging: Trace variable values and locate common logic errors such as off-by-one mistakes and infinite loops.
- Algorithm: Design a simple algorithm that combines decisions and repetition to solve a real problem.
Control Flow: Decisions and Repetition
A program normally executes instructions in sequence, one after another. Conditional statements and loops change that simple sequence. A conditional statement creates branches: only a selected path runs. A loop creates repetition: a block can run more than once.
The diamond-shaped symbol below represents a decision in a flowchart. A decision asks a question whose result determines which path the algorithm follows.

A useful way to think about control flow is to ask two questions: What decides the next step? and What makes repetition stop? If you can answer both questions, you can often predict the behavior of the program.
Conditional Logic
A conditional statement checks a condition. The condition evaluates to either true or false. If it is true, one block can run; if it is false, another block may run.

Here is a simple Python-style example:
temperature = 31
if temperature > 30:
print("Drink water")
else:
print("Normal plan")
The expression temperature > 30 is the condition. Because 31 is greater than 30, the first branch runs.
An if statement can stand alone when an action is needed only in one situation. An if/else structure is useful when exactly one of two alternatives should run. An if/elif/else chain can test several cases. In such a chain, conditions are tested in order, and the first true branch is selected.
score = 82
if score >= 90:
print("Excellent")
elif score >= 70:
print("On target")
else:
print("Keep practising")
The order matters. If a broad condition appears before a more specific condition, the broad condition may capture cases that should have reached the later branch.
For a deeper explanation of conditionals in Python, watch this CS50 lesson:
Boolean Expressions and Operators
A Boolean value is either true or false. Conditions often use comparison operators such as ==, !=, <, >, <=, and >=. Many languages also provide Boolean operators that combine or change conditions.
AND is true only when both required conditions are true. OR is true when at least one of its conditions is true. NOT reverses a Boolean value.

Suppose a school event allows entry when a student has a ticket and has arrived before the doors close:
has_ticket = True
doors_open = True
if has_ticket and doors_open:
print("Enter the event")
Compound conditions should be written so that another reader can understand the rule. When a condition becomes long, give parts of it meaningful variable names or split the logic into smaller steps.
A common programming mistake is confusing assignment with comparison. In Python and many other languages, = assigns a value, while == tests whether two values are equal. The exact symbols vary by language, so always check the rules of the language you are using.
Loops
A loop repeats a block of instructions. Each pass through the loop is an iteration. Loops are useful when you want to process a collection, repeat an action a fixed number of times, or continue until a condition changes.
Before writing a loop, identify three things: the starting state, the condition or collection that controls repetition, and the change that moves the loop toward completion. This habit prevents many logic errors.
For Loops
A for loop is often a good choice when the number of repetitions is known or when you are processing each item in a collection.
for step in range(5):
print("Practice step", step)
This loop runs five times. In Python, range(5) produces the values 0, 1, 2, 3, and 4. The loop variable changes automatically on each iteration.
A for loop is also useful for processing a list:
names = ["Amina", "Leo", "Maya"]
for name in names:
print("Hello", name)
The body runs once for each name. This pattern is clearer than manually repeating the same print instruction.
While Loops
A while loop repeats as long as its condition remains true. It is especially useful when you do not know in advance exactly how many iterations will be needed.
attempts = 0
while attempts < 3:
print("Try again")
attempts = attempts + 1
The variable attempts starts at 0 and increases on each iteration. When it reaches 3, the condition becomes false and the loop stops.
A while loop needs careful design. If the variables in its condition never change in a way that can make the condition false, the loop may continue forever. This is called an infinite loop.
A sentinel value is a special input that tells a loop to stop. For example, a data-entry program might keep accepting words until the user enters stop. Sentinels are useful when the number of inputs is not known in advance.
For a full lesson on loops, including for loops, while loops, input validation, and nested loops, watch this CS50 lesson:
Nested Loops
A nested loop is a loop inside another loop. Nested loops are useful for grids, tables, pixel patterns, board games, and combinations of items.
for row in range(3):
for column in range(4):
print(row, column)
The outer loop runs three times. For each outer iteration, the inner loop runs four times. Therefore, the print instruction runs 12 times.
Nested loops can grow expensive quickly because the inner work is repeated for every outer iteration. At this level, the key skill is to trace the two loop variables carefully and ask how many times the innermost instruction will run.
Combining Conditionals and Loops
Powerful algorithms often place a conditional inside a loop. The loop handles repetition, while the conditional decides what to do during each iteration.
scores = [72, 91, 64, 88]
for score in scores:
if score >= 70:
print("Target reached")
else:
print("More practice needed")
This program examines every score and makes a decision for each item. The same structure can classify sensor readings, check quiz answers, filter data, control a game character, or validate a series of inputs.
You can also place a loop inside a conditional. For example, a program might repeat a training sequence only if the user selects practice mode. The most important design rule is that each condition and loop should have a clear purpose.
Counters, Accumulators, and State
Programs often need to remember what has happened so far. A counter records how many times something has occurred. An accumulator builds a running total. More generally, the current values of variables form the program's state.
total = 0
for value in [4, 7, 3]:
total = total + value
print(total)
Tracing the state means recording how values change after each important line or iteration. This is one of the best ways to understand unfamiliar code.
A loop that counts from 0 may create an off-by-one error if you accidentally run one iteration too many or too few. Carefully checking the first value, the final allowed value, and the stopping condition helps prevent this error.
Tracing and Debugging
Debugging is the process of finding and fixing errors. A syntax error breaks the language rules and is often reported by the programming environment. A logic error allows the program to run but produces an incorrect result. Conditional and loop bugs are often logic errors.
Use a trace table to follow values step by step:
| Iteration | counter before update | condition | action |
|---|---|---|---|
| first | 0 | true | print and add one |
| second | 1 | true | print and add one |
| third | 2 | true | print and add one |
| after loop | 3 | false | stop |
When debugging, test boundary cases. If a condition uses a threshold, test values just below, exactly at, and just above the threshold. If a loop processes a list, test an empty list, a one-item list, and a longer list when your programming environment allows it.
Useful debugging questions include: What is the value of each variable now? Which condition was true? How many iterations have occurred? Which variable changes the loop condition? What input makes the program stop?
Choosing the Right Structure
Use a conditional when the program must choose among actions. Use a for loop when repetition follows a known count or collection. Use a while loop when repetition depends on a changing condition. Use nesting only when the problem itself has a nested structure, such as rows and columns.
A flowchart can help you test the design before writing code. A decision symbol represents a true-or-false question, while an arrow returning to an earlier point represents repetition.
Good code is not only code that works. It should also be understandable. Meaningful variable names, simple conditions, predictable loop updates, and short blocks make logic easier to test and explain.
Real-World Applications
Conditional logic and loops are used whenever a digital system responds to changing information. A game can repeat its main loop while the game is active and use conditions to react to collisions. A weather station can repeatedly read a sensor and trigger a warning when a threshold is reached. A quiz app can loop through questions and use conditions to check answers. A data-cleaning script can examine each record and keep only items that satisfy a rule.
These patterns also appear outside programming. A recipe can repeat stirring until a mixture is smooth. A sports drill can repeat for a set number of rounds. A school rule can be written as a decision: if a condition is met, choose one action; otherwise choose another. Turning such processes into algorithms helps you see where instructions are precise and where human judgment is still needed.
Interactive Tasks
Quiz: Test Your Knowledge
What does a conditional statement do? (It selects an action based on a condition) (!It repeats every instruction forever) (!It stores only text values) (!It removes all variables)
What kind of value does a basic condition produce? (A true or false value) (!A file name) (!A loop count only) (!A picture)
When is a for loop usually a good choice? (When repetitions follow a known count or collection) (!When no instruction should repeat) (!When every condition must be false) (!When a program has no data)
When is a while loop usually useful? (When repetition depends on a changing condition) (!When a program must never repeat) (!When only one variable may exist) (!When all values are text)
What is one pass through a loop called? (An iteration) (!A branch) (!A syntax) (!A comment)
What usually causes an infinite while loop? (The loop condition never becomes false) (!The program contains a list) (!The loop has a variable name) (!The code prints a message)
What does the Boolean operator AND require? (Both conditions must be true) (!Only the first condition must be false) (!Exactly one condition must be true) (!All variables must be numbers)
What is a nested loop? (A loop inside another loop) (!A condition without a result) (!A variable that cannot change) (!A comment inside a program)
What does a counter usually record? (How many times something has happened) (!The color of a flowchart) (!The name of the programming language) (!The size of every file)
Why is a trace table useful? (It shows how values and decisions change step by step) (!It automatically writes every program) (!It guarantees that code has no errors) (!It replaces all testing)
Memory Game
| Conditional | Chooses a path based on whether a condition is true or false |
| Boolean expression | Produces a true or false result |
| For loop | Repeats over a known count or collection |
| While loop | Repeats while a condition remains true |
| Iteration | One complete pass through a loop body |
| Sentinel | Special input that signals a repetition should stop |
| Counter | Variable used to record how many times something occurs |
| Nested loop | Repetition placed inside another repetition |
Drag and Drop
| Match the correct terms. | Topic |
|---|---|
| Select between alternatives | Conditional statement |
| Repeat across a collection | For loop |
| Repeat while a rule stays true | While loop |
| Combine required conditions | Boolean AND |
| Track changing values step by step | Trace table |
Crossword Puzzle
| Boolean | What kind of logic uses true and false values? |
| Iteration | What is one pass through a loop called? |
| Conditional | What kind of statement chooses a path based on a test? |
| Sentinel | What special input can signal that repetition should stop? |
| Branching | What general control-flow idea describes choosing among paths? |
| Counter | What variable is commonly increased to record repetitions? |
LearningApps
Cloze Text
Open-Ended Tasks
Easy
- Decision Tree Poster: Draw a one-page flowchart for a familiar school decision, label each true and false branch, and explain where conditional logic appears.
- Everyday Loop Hunt: Find three repeated processes in daily life, write one sentence for how each process starts, repeats, and stops, and choose whether each is more like a for loop or a while loop.
- Loop Rhythm Experiment: Create a short clap or movement pattern, repeat it a fixed number of times, then change it so that a condition decides when to stop; record what changed.
- Code Narration: Choose one short example from this course and make a one-minute audio or video explanation that narrates the program line by line.
Standard
- Input Validator Project: Design and code a small program that repeatedly asks for input until it meets a clear rule, then explain how the loop condition guarantees termination.
- Programmer Interview: Interview a programmer, robotics student, teacher, or coding-club member about one real bug involving a condition or loop; summarize the cause, debugging method, and fix.
- Survey Analyzer: Collect a small anonymous class survey, loop through the responses, use at least one condition to classify them, and present the results in a table or chart.
- Computing Space Visit: Visit a school computer lab, robotics club, makerspace, or suitable virtual coding environment and document two examples where repeated actions or decisions are used in a project.
Advanced
- Mini Game Controller: Build a small text-based or visual game that has a repeating main loop, at least two conditional branches, a score or state variable, and a clear end condition.
- Algorithm Comparison Study: Solve the same repetition problem with a for loop and a while loop, test both versions with several inputs, and write a comparison of clarity, correctness, and risk of errors.
- Grid Art Generator: Use nested loops to generate a grid, pixel pattern, or text image; predict the number of inner-loop executions before running the program and verify your prediction.
- Automation Proposal Video: Identify a repetitive task at school or home, design an algorithm that combines conditions and loops, and produce a two-minute video pitch that explains benefits, limits, and cases that still require human judgment.
Learning Assessment
- Trace Table Analysis: Given a short program with a loop and a condition, create a trace table for every iteration and justify the final output from the recorded state changes.
- Boundary Case Testing: Design tests just below, exactly at, and just above a threshold, then explain what each test reveals about the conditional logic.
- Loop Selection: For three different problems, choose a for loop or a while loop and defend each choice by referring to how repetition is controlled.
- Debugging Challenge: Repair a program that has an off-by-one error or an infinite loop, identify the faulty logic, and explain why your correction makes the program terminate correctly.
- Nested Logic Design: Create pseudocode for processing several items where each item must be classified by a condition, then explain how the loop and branch cooperate.
- Transfer Scenario: Model a real process such as a game round, sensor monitor, quiz, or queue with conditions and loops, and evaluate one situation in which your algorithm would need further rules.
Evidence of Learning
Knowledge: You can explain control flow, Boolean conditions, branches, iteration, counters, sentinel values, for loops, while loops, nested loops, and common logic errors.
Skills: You can trace variable values, predict outputs, choose suitable control structures, write clear pseudocode or code, test boundary cases, and debug faulty conditions or stopping rules.
Products: Strong evidence may include a flowchart, trace table, tested program, debugging explanation, interview summary, data-analysis artifact, grid project, or explanatory video.
Transfer: You can recognize decision and repetition patterns in unfamiliar problems, turn a real process into an algorithm, justify your design choices, and identify when a digital rule is too simple for a situation that requires human judgment.
OERs on the Topic
The English Wikipedia article on control flow gives broader background on branching and repetition in programming.
Linked Learning Areas
aiMOOC Projects
MOOCwiki · Deutsch
Nach dem Lernen ist vor dem Lernen
Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.
Zur MOOCwiki-HauptseiteMediathek
Mediathek
Mediathek wird aus dem Wiki geladen ...
Keine passenden Inhalte gefunden. Bitte ändere Suche oder Filter.
NEWSLernweltNOAH fragen