Chapter 3 Control Flow¶
In a program, Control Flow determines the order in which code executes. Mastering conditional judgments and loops allows your program to execute different branches based on different situations and efficiently process data.
Example source code used in this series: Python From Beginner to Pro Example Code
3.1 Conditional Statements (if, elif, else)¶
3.1.1 Basic Concepts and Syntax¶
Conditional statements selectively execute code blocks based on Boolean conditions (True/False).
- Single branch (if)
age = 20
if age >= 18:
print("Adult")
Output:
Adult
- Dual branch (if-else)
score = 59
if score >= 60:
print("Passed")
else:
print("Failed")
Output:
Failed
- Multi-branch (if-elif-else)
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 60:
print("C")
else:
print("D")
Output:
B
3.1.2 Boolean and Comparison/Logical Operations¶
- Boolean values:
True,False - Comparison operations:
==,!=,<,<=,>,>= - Logical operations:
and,or,not
x = 3
print(x > 2, x == 5)
n = 7
print(n > 0 and n % 2 == 1)
Output:
True False
True
3.1.3 Nested Conditional Statements¶
user = "admin"
pwd = "123"
if user == "admin":
if pwd == "123":
print("Login successful")
else:
print("Incorrect password")
else:
print("User does not exist")
Output:
Login successful
3.1.4 Conditional Expression (Ternary Operator)¶
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Output:
Adult
3.1.5 Practical Application: Leap Year Judgment¶
Rule: A leap year satisfies (divisible by 4 but not by 100) OR divisible by 400.
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap year")
else:
print("Common year")
Output:
Leap year
3.2 Loop Statements (for, while)¶
3.2.1 Basic Concepts¶
Loops repeatedly execute code blocks until the condition is not met or explicitly interrupted.
3.2.2 while Loop¶
i = 1
while i <= 3:
print(i)
i += 1
Output:
1
2
3
Avoid infinite loops: Ensure the loop condition will become False, and update variables in the loop body when necessary.
while-else: The else clause executes if the loop is not terminated by break.
i = 1
while i < 3:
print(i)
i += 1
else:
print("Loop ended normally")
Output:
1
2
Loop ended normally
3.2.3 for Loop and Iteration¶
Iterate over sequences (strings, lists, tuples, etc.):
for c in "hi":
print(c)
for item in [1, 2, 3]:
print(item)
Output:
h
i
1
2
3
Usage of range():
for i in range(3):
print(i)
for i in range(1, 4):
print(i)
for i in range(2, 7, 2):
print(i)
Output (key points):
0
1
2
1
2
3
2
4
6
for-else: The else clause executes if the loop is not terminated by break.
for i in range(3):
print(i)
else:
print("No break, executing else")
Output:
0
1
2
No break, executing else
3.2.4 Loop Selection Strategy¶
- Use
forfor small data and clear counts; usewhilefor condition-based loops. - Use
enumeratewhen you need indices while iterating over sequences. - Use
range(n)for counting andrange(start, stop[, step])for intervals.
3.3 break and continue Statements¶
3.3.1 Role and Usage of break¶
Immediately terminate the current loop.
In while loop:
i = 0
while True:
i += 1
if i == 3:
break
print(i)
Output:
3
In for loop:
for n in [1, 3, 5, 8, 9]:
if n % 2 == 0:
print("Even found:", n)
break
Output:
Even found: 8
Multi-level loops (only inner loop breaks):
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break
print(i, j)
Output (key points):
1 1
2 1
3 1
3.3.2 Role and Usage of continue¶
Skip the current iteration and proceed to the next.
for n in range(1, 6):
if n % 2 == 0:
continue
print(n)
Output:
1
3
5
3.3.3 Differences and Best Practices¶
breakterminates the loop;continueskips the current iteration.- Avoid deep nesting; refactor into functions or use flags/
any/allif necessary. - Use
any()with generators for better readability when searching for targets.
3.4 pass Statement¶
3.4.1 Concept¶
pass means “do nothing” and is used for placeholder to keep syntax complete.
3.4.2 Usage Scenarios¶
- Placeholder in functions/classes/conditions for future implementation.
def todo():
pass
class Empty:
pass
flag = False
if flag:
pass
else:
print("Else executed")
Output:
Else executed
3.4.3 Differences from Other Statements¶
passdoes not change the flow;break/continuealter loop execution.
3.5 Nested Loops and Practical Applications¶
3.5.1 Print Patterns¶
n = 5
for i in range(1, n + 1):
print("*" * i)
Output (key points):
*
**
***
****
*****
3.5.2 2D Data Processing and Summation¶
matrix = [[1, 2, 3], [4, 5, 6]]
total = 0
for row in matrix:
for num in row:
total += num
print(total)
Output:
21
3.5.3 Search Algorithm (with Early Termination)¶
matrix = [[1, 2, 3], [4, 5, 6]]
target = 5
found = False
for row in matrix:
for num in row:
if num == target:
found = True
break
if found:
break
print("Found" if found else "Not found")
Output:
Found
Improve readability with built-in functions:
nums = [1, 3, 5, 8]
print(any(n % 2 == 0 for n in nums))
Output:
True
3.5.4 Performance and Optimization Suggestions¶
- Nested loops often have \(O(n^2)\) complexity; use early
breakand pruning conditions. - Leverage built-in functions (
any,all,sum,max,min) and comprehensions for readability and speed. - Use
enumeratefor indices anditems()for key-value pairs during iteration. - Refactor complex logic into functions to reduce nesting.
3.5.5 Practical Case: Filter Valid Emails¶
emails = ["a@b.com", "bad", "c@d.com"]
valid = []
for e in emails:
if "@" not in e:
continue
valid.append(e)
print(valid)
Output:
['a@b.com', 'c@d.com']
After studying this chapter, you should be able to use conditional judgments and loops proficiently to write clearer, more reliable, and efficient control flow code in actual projects.