Programming Basics: Loops, Selection & Examples

1️⃣ WHILE and FOR Loop Example

Pseudocode

WHILE NotSolved
    Instructions here
    FOR i ← 1 TO 5
        Instructions here
    ENDFOR
    Instructions here
ENDWHILE
  

Equivalent Python Code

NotSolved = True  # You can change this condition as needed

while NotSolved:
    # Instructions here
    print("Doing something before the loop")

    for i in range(1, 6):  # 1 to 5 inclusive
        # Instructions inside FOR loop
        print(f"Iteration {i} inside FOR loop")

    # Instructions after FOR loop
    print("Doing something after the loop")

    # Example condition to stop the while loop
    NotSolved = False  # Change this when the problem is solved
  
Explanation:

2️⃣ IF Statement Example (Nested Selection)

Pseudocode

IF GameWon THEN
    Instructions here
    IF Score > HighScore THEN
        Instructions here
    ENDIF
    Instructions here
ENDIF
  

Equivalent Python Code

GameWon = True       # Example condition
Score = 120
HighScore = 100

if GameWon:
    # Instructions here
    print("You won the game!")

    if Score > HighScore:
        # Instructions inside the nested IF
        print("New high score!")
        HighScore = Score

    # Instructions after the nested IF
    print("Returning to main menu...")
  
Explanation:

3️⃣ Understanding Selection in Programming

What is Selection?

Selection means making decisions in a program — choosing which part of the code to run based on a condition. It allows the program to select different paths of execution depending on whether something is True or False.

In simple terms:

Selection = Decision-making (using IF statements or similar).

Examples of Selection in Python

Example 1: Simple IF Statement

score = 85

if score >= 50:
    print("You passed!")
  

Example 2: IF ... ELSE

score = 45

if score >= 50:
    print("You passed!")
else:
    print("You failed.")
  

Example 3: IF ... ELIF ... ELSE

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 70:
    print("Grade: B")
else:
    print("Grade: C")
  

How Selection Fits with Other Statement Types

Type What it does
Variable declarationCreate storage for data (score = 0)
Constant declarationStore fixed values (PI = 3.14159)
AssignmentChange a variable’s value (score = 10)
IterationRepeat actions (for, while)
SelectionChoose actions (if, else)
SubroutineGroup actions (def function():)

Example Combining Them All

PI = 3.14159            # constant declaration
radius = 5              # variable declaration
area = PI * radius**2   # assignment

def display_area(area): # subroutine
    print("Area:", area)

if area > 50:           # selection
    print("Big circle!")
else:
    print("Small circle!")

for i in range(3):      # iteration
    display_area(area)