Control Structures in Python

Overview

Control structures determine the flow of execution in a Python program. They allow decisions, repetition, and branching logic.

Types of Control Structures

1. Conditional Statements

if Statement

  • Executes code if a condition is true.

Example:

x = 10
if x > 5:
    print("x is greater than 5")

if-else Statement

  • Executes one block if true, another if false.

Example:

if x > 5:
    print("Greater")
else:
    print("Smaller or equal")

if-elif-else Statement

  • Checks multiple conditions in order.

Example:

if x > 10:
    print("Greater than 10")
elif x == 10:
    print("Equal to 10")
else:
    print("Less than 10")

2. Looping Structures

for Loop

  • Iterates over a sequence (list, string, range).

Example:

for i in range(5):
    print(i)

while Loop

  • Repeats as long as a condition is true.

Example:

count = 0
while count < 5:
    print(count)
    count += 1

3. Loop Control Statements

break

  • Exits the loop immediately.

Example:

for i in range(10):
    if i == 5:
        break
    print(i)

continue

  • Skips the current iteration and continues.

Example:

for i in range(5):
    if i == 2:
        continue
    print(i)

pass

  • Does nothing; acts as a placeholder.

Example:

for i in range(5):
    if i == 3:
        pass
    print(i)

4. Nested Control Structures

  • Control structures can be placed inside others.

Example:

for i in range(3):
    if i % 2 == 0:
        print(i, "is even")

5. Exception Handling (Control Flow)

  • Handles runtime errors and controls program flow.

Example:

try:
    x = int("abc")
except ValueError:
    print("Conversion failed")
finally:
    print("Done")

Summary

  • Conditional statements control decision-making.

  • Loops handle repetition.

  • Loop controls modify execution within loops.

  • Exception handling manages errors and flow control.