Cyber Services / All lessons / Python Programming / Loops

Loops

Module 8 of 31 · 2 min read · Free to read

MODULES ↓ Command blocks have a COPY button
Program Control Flow

Loops allow a program to repeat a block of code multiple times. This avoids writing the same code over and over.

Basic Loop Constructs

Python has two main loop types:

  • while loop: Repeats as long as a condition is True.
  • for loop with range(): Repeats a known number of times.

1. while Loop

count = 1
while count <= 3:
    print("Count:", count)
    count = count + 1

⚠️ Always update the loop variable (count) to avoid infinite loops!

2. for Loop (using range)

for i in range(3):        # i = 0, 1, 2
    print("Step", i + 1)

range(n) generates numbers from 0 to n-1.

3. Nested Loops

A loop inside another loop. Use carefully—can become slow.

for i in range(2):
    for j in range(3):
        print("i =", i, "j =", j)

10 Best Loop Examples (Using Only Variables, I/O & Operators)

All examples use only: variables, constants, input(), print(), and arithmetic/comparison/logical operators.

1. Countdown Timer
start = int(input("Start from: "))
while start >= 0:
    print(start)
    start = start - 1
print("Blast off!")
2. Sum of First N Numbers
n = int(input("Enter N: "))
total = 0
i = 1
while i <= n:
    total = total + i
    i = i + 1
print("Sum:", total)
3. Multiplication Table
num = int(input("Number: "))
for i in range(1, 11):  # 1 to 10
    print(num, "x", i, "=", num * i)
4. Repeat Until Valid Input
age = -1
while age < 0 or age > 120:
    age = int(input("Enter valid age (0-120): "))
print("Age accepted:", age)
5. Print Even Numbers
n = int(input("Up to: "))
i = 2
while i <= n:
    print(i)
    i = i + 2
6. Factorial (Using while)
n = int(input("Enter number: "))
fact = 1
i = 1
while i <= n:
    fact = fact * i
    i = i + 1
print("Factorial:", fact)
7. Power Calculator (x^n)
base = int(input("Base: "))
exp = int(input("Exponent: "))
result = 1
i = 0
while i < exp:
    result = result * base
    i = i + 1
print("Result:", result)
8. Digit Counter
num = int(input("Enter a positive number: "))
count = 0
temp = num
while temp > 0:
    count = count + 1
    temp = temp // 10
print("Digits in", num, ":", count)
9. Simple Progress Bar
steps = 5
for i in range(steps):
    print("[" + "=" * (i + 1) + " " * (steps - i - 1) + "]")
# Output: [=    ], [==   ], ...
10. Nested: Rectangle of Stars
rows = int(input("Rows: "))
cols = int(input("Columns: "))
for r in range(rows):
    line = ""
    for c in range(cols):
        line = line + "*"
    print(line)

Key Takeaways

  • Use while when the number of repetitions is unknown.
  • Use for with range() for fixed counts.
  • Always update loop variables to prevent infinite loops.
  • Nested loops multiply iterations (e.g., 3×4 = 12 steps).
  • Loops + operators = powerful automation with minimal code.
Modules (31) ← Python Programming