Zum Inhalt springen

English:Selection in Programming

Aus MOOCsWiki Staging
Version vom 12. August 2026, 12:43 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)

Selection in Programming



Introduction

Selection is the part of a program that lets the computer make a decision. Instead of always following the same instructions, the program checks a condition and chooses what to do next. You meet the same idea in everyday life: if it is raining, take a coat; otherwise, leave the coat at home.

In programming, selection is often written with words such as if, else, and sometimes elif or else if. These words create different branches in the program. The branch that runs depends on whether a condition is true or false.

Selection works together with sequence and iteration. Sequence puts instructions in order, selection chooses between paths, and iteration repeats instructions.


Learning Goals

By the end of this aiMOOC, you should be able to explain how selection changes program flow, write and trace simple if and if-else structures, build useful Boolean conditions, draw decision flowcharts, test boundary cases, find common logic errors, and apply selection to small programs and games.


How Selection Works

A program using selection usually follows three steps. First, it gathers or calculates some data. Next, it tests a condition. Finally, it runs one branch when the condition is true and a different branch when the condition is false.

Imagine a game with a door that opens only when the player has a key. The condition could be player has key. If the condition is true, the program opens the door. If the condition is false, the program displays a message such as "You need a key."


Boolean Conditions

A condition must be something the computer can treat as true or false. A value with only these two possibilities is called a Boolean value.

Common comparison operators include:

Operator Meaning Example Result
== equal to score == 10 true when score is 10
!= not equal to lives != 0 true when lives is not 0
> greater than temperature > 25 true when temperature is above 25
< less than speed < 50 true when speed is below 50
>= greater than or equal to age >= 13 true when age is 13 or more
<= less than or equal to points <= 100 true when points is 100 or less

Be careful with the difference between assignment and comparison. In languages such as Python, a single equals sign assigns a value, while two equals signs compare values.


AND, OR, and NOT

You can combine simple conditions to make more precise decisions.

AND is true only when all connected conditions are true. For example, a game might unlock a level when the player has a key AND has at least 50 points.

OR is true when at least one connected condition is true. A club website might allow entry when a person is a member OR has a guest pass.

NOT reverses a Boolean value. If is_locked is true, then NOT is_locked is false.


If Statements

An if statement runs a block of code only when its condition is true.

temperature = 28

if temperature > 25:
    print("It is warm.")

If the temperature is 28, the message is shown. If the temperature is 25 or lower, the program skips that indented instruction.

Selection does not have to use numbers. A program could compare text, check a Boolean variable, or test whether an object has reached a position.


If-Else Statements

An if-else statement provides two paths. One path runs when the condition is true, and the other runs when it is false.

age = 13

if age >= 13:
    print("Age 13 or over")
else:
    print("Child ticket")

The two branches should represent clear alternatives. In this example, every possible age goes into one of the two branches, although a real ticket system might add more age groups.

The image uses the C programming language, but the same decision pattern appears in many programming languages.


More Than Two Choices

Sometimes a program needs more than two possible outcomes. Python can use elif to test another condition after the first condition is false.

score = 74

if score >= 90:
    print("Gold")
elif score >= 70:
    print("Silver")
else:
    print("Bronze")

The order of conditions matters. The program checks from top to bottom and uses the first branch whose condition is true. This means broad conditions placed too early can prevent more specific branches from ever running.


Flowcharts for Selection

A flowchart is a visual way to represent an algorithm. A decision is commonly shown with a diamond. One path leaves the diamond for one result, such as true or yes, and another path leaves it for the other result, such as false or no.

Before coding, a flowchart can help you check whether every important outcome has a path. It can also make missing cases easier to notice.

For example, imagine a program that recommends what to do after school. A decision could ask, "Is homework finished?" The yes branch could suggest a hobby. The no branch could suggest finishing the homework first.


Nested Selection

A selection statement can appear inside another selection statement. This is called nested selection.

Suppose a school game first checks whether a player has enough points. If the player does, it then checks whether the player has a special badge. The second decision happens only after the first condition is true.

Nested selection can solve complex problems, but too many levels can make code difficult to read. Sometimes a combined condition using AND or OR can express the same idea more clearly.


Selection in Games and Apps

Selection makes programs interactive. It can control whether a character jumps, whether a password is accepted, whether a quiz answer earns a point, whether a warning appears, or whether a game changes level.

In a block-based environment such as Scratch, an if block can check touching, key presses, scores, timers, or variable values. In text-based languages such as Python, the same idea is written with indentation and keywords.


Example: A Simple Quiz

answer = input("Which planet is known as the Red Planet? ")

if answer == "Mars":
    print("Correct!")
else:
    print("Try again.")

This program contains one condition and two possible outputs. A stronger version could accept different capitalizations, keep a score, or give a hint after an incorrect answer.


Testing and Debugging Selection

A selection statement can be syntactically correct and still make the wrong decision. This is a logic error. Good testing checks more than one input.

For a condition such as age >= 13, useful test values include 12, 13, and 14. The value 13 is especially important because it is the boundary where the decision changes.

When debugging selection, ask yourself whether the comparison operator is correct, whether the branches are in the right order, whether every important case is covered, and whether a condition can ever be true.

A trace table can help. Write down the input values, evaluate each condition, and record which branch runs. This turns guessing into a clear step-by-step check.


Common Mistakes

A common mistake is using > when >= is needed. Another is testing conditions in an order that makes a later branch unreachable. A third is forgetting that text comparisons may depend on spelling and capitalization.

Indentation also matters in languages such as Python because it shows which instructions belong to a branch. In block-based languages, the shape and nesting of blocks show this structure visually.


Responsible Use of Selection

Selection is powerful because it lets software make choices. That means programmers should think carefully about the rules they create. A rule can be technically correct but still be unfair, unsafe, or based on poor data.

For school projects, use selection to solve clear problems and avoid unnecessary use of personal information. When a decision affects people, explain the condition in plain language and test whether it behaves as intended for different cases.


Extending Your Thinking

More advanced programs may use many related decisions. Some languages provide structures such as switch or match for choosing among several fixed cases. The exact syntax differs between languages, but the central idea remains the same: evaluate information and choose an appropriate branch.


Interactive Tasks


Quiz: Test Your Knowledge

What is the main purpose of selection in a program? (To choose between different paths) (!To repeat instructions forever) (!To store every value as text) (!To turn code into an image)




What kind of result should a basic condition produce? (True or false) (!A picture or sound) (!A file name) (!A random color)




Which keyword usually starts a basic selection statement? (if) (!repeat) (!print) (!import)




What does an else branch do? (Runs when the if condition is false) (!Runs before every condition) (!Repeats the if branch) (!Deletes the condition)




Which comparison checks whether two values are equal in Python? (Two equals signs) (!One equals sign) (!One greater than sign) (!One less than sign)




When is an AND condition true? (When all connected conditions are true) (!When every condition is false) (!When exactly one condition is written) (!Whenever a variable contains text)




Why is a boundary value useful in testing? (It checks where a decision changes) (!It makes the program run faster) (!It replaces all other test data) (!It creates a new variable automatically)




What does a diamond usually represent in a flowchart? (A decision) (!A printed message) (!A stored file) (!A program title)




What is nested selection? (A selection statement inside another selection statement) (!A loop that never stops) (!A variable inside a string) (!A comment inside a flowchart)




What is a logic error in selection? (The program runs but makes the wrong decision) (!The monitor is switched off) (!The keyboard has no space key) (!The file has a long name)





Memory Game

Condition A test that is evaluated as true or false
Branch One possible path through a selection structure
Boolean A data type with the values true and false
Comparator An operator that compares two values
Boundary A value where the outcome of a decision can change
Nesting Placing one selection structure inside another





Drag and Drop

Match the correct terms. Topic
if Starts a condition check
else Gives an alternative branch
AND Requires all connected conditions to be true
OR Requires at least one connected condition to be true
NOT Reverses a Boolean value




...


Crossword Puzzle

Condition What is a true-or-false test called?
Boolean What data type has only true and false values?
Branch What is one possible path through a decision called?
Comparator What kind of operator compares two values?
Nested What word describes selection placed inside selection?
Flowchart What diagram uses shapes and arrows to show an algorithm?





LearningApps


Cloze Text

Complete the text.

Selection lets a program

between different paths. A true-or-false test is called a

. An if statement runs its branch when the condition is

. An else branch provides an

. The logical operator

requires all connected conditions to be true. A decision is often shown as a

in a flowchart. Testing the value where an outcome changes checks a

. A selection statement placed inside another one is called

.




Open-Ended Tasks


Easy

  1. Everyday Decision Algorithm: Write five everyday if-then decisions and turn one of them into a simple flowchart.
  2. Two-Choice Story: Create a short interactive story with one decision and two different endings.
  3. Condition Cards: Make illustrated cards showing five conditions and label each possible result as true or false for a chosen example.
  4. Selection Screenshot Explanation: Build one if or if-else structure in a block-based programming tool, capture an image of it, and explain what each branch does.


Standard

  1. Quiz Program Project: Create a three-question quiz that uses selection to check answers and update a score.
  2. Weather Adviser Program: Design a program that recommends an action from temperature and rain information using at least two conditions.
  3. Flowchart to Code: Draw a flowchart with at least three outcomes and then implement the same logic in a programming language.
  4. Peer Debugging Interview: Interview a classmate about a selection bug they found, reproduce the bug, and document how it was fixed.


Advanced

  1. Boundary Testing Investigation: Create a program with at least two numerical boundaries, design a test table around those boundaries, and explain the results.
  2. Nested Selection Game: Build a small game that uses nested selection for a meaningful gameplay decision, then redesign one part to reduce unnecessary nesting.
  3. Fair Decision Rules: Investigate a real or imagined automated decision system, identify the conditions it might use, and propose changes that make the rules clearer and fairer.
  4. Selection Tutorial Video: Produce a short teaching video that explains if, else, Boolean conditions, flowcharts, and one debugging strategy with your own examples.



Learning Assessment

  1. Trace a Selection Program: Given a short program with several inputs, predict each branch that runs and justify every prediction by evaluating the conditions.
  2. Design from Requirements: Convert a written set of rules for a school club or game into a flowchart and working selection structure, then explain how each rule maps to a branch.
  3. Debug a Boundary Error: Repair a program that handles a boundary incorrectly, show the failing and passing test cases, and explain why the changed operator fixes the problem.
  4. Compare Two Solutions: Solve the same decision problem once with nested selection and once with combined Boolean operators, then evaluate which version is clearer.
  5. Evaluate Decision Coverage: Inspect a multi-branch algorithm, identify any missing or unreachable cases, and propose a corrected order of conditions.
  6. Transfer to a New Context: Apply selection to a new situation such as a sensor, game, quiz, or recommendation tool and explain what data, conditions, and outputs are required.




Evidence of Learning

Knowledge
You can explain selection, conditions, Boolean values, comparison operators, branches, logical operators, nested selection, flowchart decisions, and boundary testing.
Skills
You can write and trace if, if-else, and multi-branch structures; combine conditions; draw flowcharts; test important cases; and debug logic errors.
Products
Useful evidence can include a working program, an annotated flowchart, a test table, a debugging record, a storyboard, or a short tutorial video.
Transfer
You can recognize a decision problem in a new context and choose suitable conditions, branches, and tests instead of copying a memorized example.




OERs on the Topic



Linked Learning Areas

Selection connects programming with algorithms, logic, mathematics, game design, digital citizenship, and problem solving. Understanding it also prepares you for more complex topics such as loops, functions, input validation, and event-driven programs.


aiMOOC Projects