You're offline — cached pages and worlds still work
Drishti Innovations logo
Drishti Innovations

Control Structures (Loops & Conditionals)

Conditional branching (if-else) and loops (for, while) in Python. Aligned with RRT Path Planner visualizer.

Control Structures (Loops & Conditionals)

Control Structures — Loops & Conditionals

What you'll learn

  • Use if/elif/else to branch program logic.
  • Iterate with for and while loops.
  • Use break, continue, and pass.
  • Write nested loops and loop-else clauses.

Key concepts

if / elif / else

score = int(input("Score: "))

if score >= 90:
    print("A")
elif score >= 75:
    print("B")
elif score >= 60:
    print("C")
else:
    print("Fail")
  • Conditions evaluate to True or False.
  • elif = "else if" — only checked if previous conditions are False.
  • Only the first matching branch executes.

Ternary Expression (one-liner)

label = "Pass" if score >= 60 else "Fail"

for Loop

for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

for char in "Python":     # iterates characters
    print(char)

for item in [1, 2, 3]:    # iterates list
    print(item)

range(start, stop, step):

range(2, 10, 2)   # 2, 4, 6, 8
range(10, 0, -1)  # 10, 9, ..., 1

while Loop

n = 1
while n <= 5:
    print(n)
    n += 1
  • Runs while condition is True.
  • Must update loop variable to avoid infinite loop.

break and continue

for i in range(10):
    if i == 5:
        break       # exit loop immediately
    if i % 2 == 0:
        continue    # skip rest of this iteration
    print(i)        # prints 1, 3  (stops at 5)
KeywordEffect
breakExit the loop entirely
continueSkip to next iteration
passDo nothing (placeholder)

Nested Loops

for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end="\t")
    print()

Outer loop controls rows; inner controls columns.

Loop with else

for i in range(2, n):
    if n % i == 0:
        print("Not prime")
        break
else:
    print("Prime")   # runs only if loop completed without break

Common Patterns

Sum of numbers:

total = 0
for i in range(1, 101):
    total += i
print(total)   # 5050

Factorial:

n = int(input())
fact = 1
for i in range(1, n + 1):
    fact *= i
print(fact)

Checking prime:

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

Quick check

  • Write a for loop to print all even numbers from 2 to 20.
  • What is the difference between break and continue?
  • Write a while loop to print the Fibonacci sequence up to 100.
  • What does the else clause of a for loop do?
  • What is the output of range(1, 10, 3)?

Open the Practice tab for graded questions on Control Structures.

Key Takeaways (TL;DR)

  • What you'll learn
  • Key concepts
  • Quick check

Master this topic with Drishti OS

Get unlimited mock tests, AI-powered mentorship, and complete video courses when you join.

Start Free Practice