Master Python control flow using if-else conditions, loops, and comprehensions. Learn how to write efficient, readable, and dynamic programs.
Objective:
Learn to control the execution flow of Python programs using conditions, loops, and comprehensions to perform repeated or conditional tasks efficiently.
Topics and Examples:
1. Conditional Statements: if, elif, else
Conditional statements allow Python to execute code only when certain conditions are met.
Example:
age = 18
if age >= 18:
print("You are an adult.")
elif age > 12:
print("You are a teenager.")
else:
print("You are a child.")
2. Loops: for and while
Loops are used to execute a block of code multiple times.
For Loop Example:
# Print numbers from 0 to 4
for i in range(5):
print(i)
While Loop Example:
count = 0
while count < 5:
print(count)
count += 1
3. Loop Control Statements: break, continue, pass
break– exits the loop immediatelycontinue– skips the current iteration and moves to the nextpass– does nothing, acts as a placeholder
Example:
for i in range(5):
if i == 2:
continue # Skip the number 2
if i == 4:
break # Exit loop when i is 4
print(i)
# pass example
for i in range(3):
pass # Placeholder for future code
Output:
0
1
3
4. List Comprehensions & Dictionary Comprehensions
Comprehensions allow creating lists or dictionaries in a single line, making code concise and readable.
List Comprehension Example:
# Create a list of squares
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
Dictionary Comprehension Example:
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
This section covers all Python control flow basics: conditional statements, loops, loop control, and comprehensions, with practical examples to practice and master.