Control Flow Statements 🔄: Conditional Logic and Loops

Intermediate

Control flow in Python allows you to execute code selectively or repeatedly, enabling dynamic behavior.

Conditional Statements: Use if, elif, and else to execute code based on conditions.

age = 20
if age >= 18:
    print('Adult')
elif age >= 13:
    print('Teen')
else:
    print('Child')

Loops:

  • for loops iterate over sequences like lists or ranges.
  • while loops repeat as long as a condition holds.
# For loop
for i in range(5):
    print(i)

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

Break and Continue: Control loop execution.

for i in range(10):
    if i == 5:
        break  # Exit loop
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)

Control flow structures are essential for implementing complex logic and decision-making in programs.