ποΈ Control Flow and Loops
Control flow allows a program to make decisions, repeat actions, and direct the execution path based on conditions. Python includes several constructs for managing control flow, primarily through conditional statements and looping mechanisms.
π 1. Conditional Statements:
ifStatement Used to execute code only if a condition is true:
if_statement.py
x = 10
if x > 5:
print("x is greater than 5")if-elseStatement Provides an alternative path if the condition is false:
if_else_statement.py
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")elif(Else If) Used for multiple conditions:
elif_statement.py
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is exactly 10")
else:
print("x is less than 10")π 3. Loops:
- while Loop Repeats a block of code as long as the condition is true:
while_loop.py
count = 0
while count < 5:
print("Count:", count) # Output: Count: 0, Count: 1, Count: 2, Count: 3, Count: 4
count += 1- for Loop Iterates over a sequence (list, tuple, string, etc.):
for_loop.py
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) # Output: apple, banana, cherry
# Using range() in for Loops
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# With start, stop, step:
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9control_loops.py
# Loop Control Statements
for i in range(10):
if i == 5:
break # Exits the loop prematurely
print(i)
for i in range(10):
if i % 2 == 0:
continue # Skips the current iteration and continues with the next
print(i) # 1, 3, 5, 7, 9
for i in range(5):
print(i)
else:
# The else block executes if the loop completes normally (i.e., not interrupted by break)
print("Loop finished without break")nested_loops.py
# Loops within loops
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")example.py
# Finding Prime Numbers
for num in range(2, 20):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a prime number")Last updated on