Chapter 3: Control Flow
1. Conditional Statements
Conditional statements execute different code blocks based on conditions.
1.1 if Statement
if StatementThe simplest form of control flow. If a condition is True, the code inside the if block is executed.
Syntax:
if condition:
# Code to execute if the condition is TrueExample:
age = 18
if age >= 18:
print("You are an adult.")1.2 if-else Statement
if-else StatementProvides an alternative code block if the condition is False.
Syntax:
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is FalseExample:
num = 10
if num % 2 == 0:
print("Even number.")
else:
print("Odd number.")1.3 if-elif-else Statement
if-elif-else StatementTests multiple conditions in sequence.
Syntax:
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if none of the above conditions are TrueExample:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")1.4 Nested if Statements
if Statementsif statements can be nested for more complex conditions.
Example:
age = 20
has_id = True
if age >= 18:
if has_id:
print("Access granted.")
else:
print("ID required.")
else:
print("Access denied.")1.5 Ternary Conditional Expression
A one-liner for if-else statements.
Syntax:
value = true_value if condition else false_valueExample:
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)1.6 Precautions with Conditionals
Proper Indentation: Python relies on indentation to define blocks. A mismatch will cause errors.
Avoid Overcomplicating: Use
elifinstead of nesting multipleifstatements.Boolean Values: Avoid redundancy. For example, instead of:
if x == True:Simply use:
if x:
2. Loops
Loops allow you to execute code repeatedly.
2.1 while Loop
while LoopRepeats as long as a condition is True.
Syntax:
while condition:
# Code to execute repeatedlyExample:
count = 0
while count < 5:
print(count)
count += 1Precautions:
Infinite Loops: Ensure the condition eventually becomes
False.Use a
breakstatement to exit loops if necessary.
2.2 for Loop
for LoopIterates over a sequence (e.g., list, string, range).
Syntax:
for variable in sequence:
# Code to execute for each item in the sequenceExample:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)2.3 range() in for Loops
range() in for LoopsThe range() function generates a sequence of numbers, commonly used in for loops.
Examples:
for i in range(5): # 0 to 4
print(i)
for i in range(2, 10, 2): # Start at 2, end at 9, step by 2
print(i)2.4 break and continue
break and continuebreak: Exit the loop entirely.continue: Skip to the next iteration.
Examples:
for i in range(5):
if i == 3:
break
print(i) # Stops when i == 3
for i in range(5):
if i == 2:
continue
print(i) # Skips i == 22.5 Nested Loops
Loops inside other loops.
Example:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")3. Control Flow Tools
3.1 The pass Statement
pass StatementDoes nothing; acts as a placeholder.
Example:
if True:
pass # Placeholder for future code3.2 The else Clause in Loops
else Clause in LoopsA for or while loop can have an else clause. The else block runs if the loop completes normally (i.e., no break).
Example:
for i in range(5):
if i == 3:
break
else:
print("Loop completed.")4. Comprehensions
4.1 List Comprehensions
A concise way to create lists.
Example:
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]4.2 Dictionary Comprehensions
Create dictionaries in one line.
Example:
squared_dict = {x: x**2 for x in range(5)}
print(squared_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}5. Precautions and Tricks
Avoid Infinite Loops:
Always ensure the loop condition will eventually be
False.
Keep Logic Simple:
Use comprehensions where possible for clarity and efficiency.
Don’t Modify a Collection While Iterating:
If you need to modify a list while looping, iterate over a copy:
for item in list(items): items.remove(item)
elsein Loops:Remember that the
elseblock executes only if the loop wasn't terminated bybreak.
Summary Table: Control Flow Tools
if
Executes block if condition is True.
if x > 5: print(x)
if-else
Adds an alternative block.
if x > 5: ... else: ...
if-elif-else
Tests multiple conditions.
if x > 5: ... elif x == 5: ...
while
Repeats as long as condition is True.
while x < 5: ...
for
Iterates over a sequence.
for item in list: ...
break
Exits the loop entirely.
if x == 3: break
continue
Skips to the next iteration.
if x == 3: continue
pass
Does nothing (placeholder).
if x > 5: pass
else in loops
Executes if loop completes normally.
for x in range(5): ... else: ...
Comprehensions
One-line list or dict creation.
[x**2 for x in range(5)]
Last updated