Python Control Flow
Control flow in Python allows you to make decisions and repeat actions using conditional statements and loops. This tutorial explores how to use if
, elif
, else
, and loop structures to control your program’s execution.
01. What Is Control Flow?
Control flow determines the order in which your code executes, enabling dynamic behavior based on conditions or iterations. Python provides conditional statements (if
) and loops (for
, while
) for this purpose.
Example: Basic Control Flow
# Conditional statement
age = 20
if age >= 18:
print("You are an adult") # Executes if condition is True
# Loop
for i in range(3):
print(f"Iteration {i}") # Repeats 3 times
Output:
You are an adult
Iteration 0
Iteration 1
Iteration 2
Explanation:
if age >= 18
- Checks a condition and executes the block if true.for i in range(3)
- Iterates over a sequence, executing the block for each value.
02. Conditional Statements
Conditional statements allow your program to execute different code based on conditions using if
, elif
, and else
.
2.1 Using if, elif, else
Example: Conditional Logic
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Output:
Grade: B
2.2 Nested Conditionals
Example: Nested if Statements
age = 16
has_permit = True
if age >= 16:
if has_permit:
print("You can drive with a permit")
else:
print("You need a permit to drive")
else:
print("You are too young to drive")
Output:
You can drive with a permit
2.3 Invalid Conditional Syntax
Example: Syntax Error
if 5 > 3 # Missing colon (SyntaxError)
print("This won't work")
Output:
SyntaxError: expected ':'
Explanation:
if 5 > 3
- Missing a colon (:
) causes aSyntaxError
.
03. Loops
Loops allow you to repeat code blocks using for
or while
statements.
3.1 For Loops
Example: For Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"Fruit: {fruit}")
Output:
Fruit: apple
Fruit: banana
Fruit: cherry
3.2 While Loops
Example: While Loop
count = 1
while count <= 3:
print(f"Count: {count}")
count += 1
Output:
3.3 Infinite Loop Error
Example: Infinite Loop
while True:
print("This runs forever!") # Infinite loop (avoid unless intentional)
Output:
This runs forever! (Repeats indefinitely)
Explanation:
while True
- Runs indefinitely unless interrupted (e.g., Ctrl+C).
04. Loop Control Statements
Use break
, continue
, and pass
to modify loop behavior.
Example: Break and Continue
for i in range(5):
if i == 2:
continue # Skip this iteration
if i == 4:
break # Exit loop
print(f"Number: {i}")
Output:
Number: 0
Number: 1
Number: 3
05. Effective Usage
5.1 Recommended Practices
- Keep conditions simple and readable.
Example: Clear Conditions
# Good: Simple condition
if temperature > 30:
print("It's hot!")
# Avoid: Overly complex
if temperature > 30 and not is_raining and wind_speed < 20:
print("It's a nice day!")
- Use
break
to exit loops early when possible. - Ensure loops have a clear exit condition to avoid infinite loops.
5.2 Practices to Avoid
- Avoid deeply nested conditionals or loops (aim for 2-3 levels max).
Example: Excessive Nesting
# Avoid: Hard to read
if x > 0:
if y > 0:
if z > 0:
print("All positive")
- Don’t forget to update loop variables in
while
loops.
06. Common Use Cases
6.1 User Input Validation
Use conditionals to validate user input before processing.
Example: Input Validation
age = int(input("Enter your age: "))
if age < 0 or age > 120:
print("Invalid age!")
else:
print(f"You are {age} years old")
Output:
Enter your age: 25
You are 25 years old
6.2 Processing Lists
Loops are ideal for iterating over collections like lists.
Example: Summing a List
numbers = [10, 20, 30]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
Output:
Sum: 60
Conclusion
Python’s control flow tools—conditionals and loops—enable dynamic and repetitive tasks in your programs. By mastering if
, for
, and while
, you can build flexible, efficient code. Key takeaways:
- Use
if
,elif
,else
for decision-making. - Iterate with
for
for sequences andwhile
for condition-based loops. - Control loops with
break
andcontinue
for efficiency. - Keep conditions and loops simple to avoid errors like infinite loops.
With these skills, you’re ready to create dynamic Python programs with ease!
Comments
Post a Comment