Control flow statements dictate the order in which the code is executed. Python provides conditional statements, loops, and control modifiers to manage program flow.
1. Conditional Statements
Conditional statements execute different blocks of code based on specific conditions.
if Statement
Executes a block of code if a condition is true.
x = 10
if x > 5:
print("x is greater than 5")
if…else Statement
Executes one block of code if the condition is true, otherwise another block.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
if…elif…else Statement
Checks multiple conditions.
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but not more than 10")
else:
print("x is 5 or less")
2. Loops
Loops allow you to execute a block of code repeatedly.
for Loop
Used to iterate over a sequence (list, tuple, string, etc.).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while Loop
Executes a block of code as long as a condition is true.
count = 0
while count < 5:
print("Count is", count)
count += 1
3. Loop Control Statements
Control statements modify the behavior of loops.
break Statement
Exits the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
continue Statement
Skips the current iteration and moves to the next.
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints odd numbers
pass Statement
Does nothing and is used as a placeholder.
for i in range(5):
if i == 3:
pass # Placeholder for future code
print(i)
4. Nested Control Flow
You can nest if
statements and loops for more complex logic.
Nested if
x = 8
if x > 5:
if x % 2 == 0:
print("x is greater than 5 and even")
Nested Loops
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
5. Example: Combining Control Flow
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Control flow structures help in building logic and managing the execution path of a program effectively.
One response
Learned alot from this course, recommended.