Python Control Flow
中文版:Python 控制流
Control flow structures determine the order in which statements are executed, including conditionals and loops.
Definition
Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated. Python provides if statements for conditional branching and for / while loops for repetition.
Info
Python uses indentation (4 spaces or a tab) to define code blocks. Colons
:are used to start blocks.
If Statements
num = float(input("Enter a number: "))
if num > 0:
print("Positive!")
elif num < 0:
print("Negative!")
else:
print("Zero!")Combining Conditions
Comparison operators (==, !=, >, <, >=, <=) and logical operators (and, or, not) can be combined:
num = 15
if 10 <= num <= 20:
print("In range!")
else:
print("Out of range!")
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "1234":
print("Login successful!")
else:
print("Invalid credentials.")For Loops
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)
# Sum all numbers in a list
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Sum:", total) # 15While Loops
# Countdown from 5 to 1
count = 5
while count > 0:
print(count)
count -= 1Continue and Break
continue: Skips the rest of the current iteration and moves to the next.break: Exits the loop immediately.
# Skip even numbers using continue
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints 1, 3, 5, 7, 9
# Stop loop when a condition is met using break
for num in range(1, 100):
if num % 7 == 0:
print("First multiple of 7:", num) # 7
breakNested Loops
# Multiplication table (1 to 3)
for i in range(1, 2):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print("------")Common Misconceptions
- Forgetting colons: Every
if,elif,else,for,while,def, andclassstatement must end with a colon. - Inconsistent indentation: Mixing tabs and spaces can cause
IndentationError.
Related Concepts
- Python Variables — Variables used in conditions and loops
- Python Data Types — Collections iterated over in loops
- Introduction to Python — The lecture covering these topics