For Loops and While Loops
1. For Loops
Purpose:
Used to iterate over a sequence (like a list, string, tuple, range, etc.)
Syntax:
for variable in iterable:
# code block
Example 1: Looping through a list
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Using range()
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(n) gives numbers from 0 to n-1
You can also use:
range(start, stop, step)
Example 3: Loop with index (using enumerate())
colors = [“red”, “green”, “blue”]
for index, color in enumerate(colors):
print(f”{index}: {color}”)
When to use for:
- You know how many times to loop
- You’re iterating over a list, string, or range
- You want clean, readable iteration
2. While Loops
Purpose:
Repeats a block of code as long as a condition is True.
Syntax:
while condition:
# code block
Example 1: Basic while loop
count = 0
while count < 5:
print(“Count is:”, count)
count += 1
Example 2: User input loop
password = “”
while password != “secret”:
password = input(“Enter the password: “)
print(“Access granted.”)
When to use while:
- You don’t know in advance how many times to loop
- You’re waiting for a condition to be met
- Great for input validation, menus, waiting for user action, etc.
Control Flow Keywords (work in both loops)
Keyword | Use |
---|---|
break |
Exits the loop immediately |
continue |
Skips remaining code in current iteration and moves to next iteration |
else |
Optional block that executes only if loop completes normally (without break ) |
break Example:
for num in range(10):
if num == 5:
break
print(num)
continue Example:
for num in range(5):
if num == 2:
continue
print(num)
Summary: for vs while
Feature | for Loop | while Loop |
---|---|---|
Iterates over | Sequence (range , list , string ) |
Until a condition becomes False |
Use when | You know how many iterations needed | You don’t know how many iterations needed |
Example Use | Printing list items, counting | Waiting for correct user input |
Want More?
I can add:
- Loop exercises (countdown timer, sum calculator, etc.)
- A quiz or worksheet
- A visual loop flowchart
- Let me know what format you’d like next!
Break, Continue, and Pass
1. break – Exit the loop early
What it does:
Immediately terminates the nearest enclosing loop — either for or while.
Syntax:
for item in iterable:
if condition:
break
Example:
for num in range(10):
if num == 5:
break
print(num)
Output:
0
1
2
3
4
The loop stops before 5, because break exits the loop.
Real Use Case:
- Exiting on a condition (e.g. stop searching when found)
- Validating passwords or attempts
2. Continue – Skip this iteration
What it does:
Skips the rest of the code in the current loop iteration, and moves to the next one.
Syntax:
for item in iterable:
if condition:
continue
# code here will be skipped if condition is True
Example:
for num in range(5):
if num == 2:
continue
print(num)
Output:
0
1
3
4
When num == 2, it skips the print() and goes to the next loop.
Real Use Case:
- Skipping invalid data
- Ignoring certain values (e.g., skip vowels or zeroes)
3. pass – Do nothing (placeholder)
What it does:
Literally does nothing — used when a statement is syntactically required but you don’t want any code to run.
Syntax:
if condition:
pass # Do nothing (for now)
Example:
for num in range(3):
if num == 1:
pass
print(f”Number is {num}”)
Output:
Number is 0
Number is 1
Number is 2
The pass does nothing — but it lets the if statement exist without error.
Real Use Case:
- Placeholder for code you’ll write later
- Empty function or class definitions
- Keeping structure while under development
Summary Table:
Keyword | Purpose | Ends Loop? | Skips Iteration? | Use Case |
---|---|---|---|---|
break |
Exits loop immediately | ✓ | X | Stop a loop early (e.g., on match) |
continue |
Skips rest of current iteration | X | ✓ | Skip unwanted data |
pass |
Does nothing; placeholder | X | X | Keep syntax valid without logic |
Bonus Practice Ideas:
- Loop through numbers and break when divisible by 7
- Skip even numbers using continue
- Create an empty function using pass
Looping through strings, lists, and ranges
You can use for loops to iterate over sequences in Python — like strings, lists, and ranges — because they’re all iterables.
1. Looping Through a String
Purpose:
Each character in a string can be accessed one by one.
Syntax:
for char in string:
# do something with char
Example:
word = “Python”
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Use Cases:
- Counting vowels
- Reversing or analyzing text
- String transformations
2. Looping Through a List
Purpose:
Iterate through each item (element) in a list.
Syntax:
for item in list_name:
# do something with item
Example:
colors = [“red”, “green”, “blue”]
for color in colors:
print(color.upper())
Output:
RED
GREEN
BLUE
Looping with enumerate():
for index, color in enumerate(colors):
print(f”{index}: {color}”)
Use Cases:
- Displaying indexed menus
- Searching or filtering
- Data transformation
3. Looping Through a Range
Purpose:
Use range() to generate a sequence of numbers, which can be used for indexed loops or counters.
Syntax:
for i in range(stop)
for i in range(start, stop)
for i in range(start, stop, step)
Example 1: Basic Range
for i in range(5):
print(i)
Output:
0
1
2
3
4
Example 2: Start and Stop
for i in range(2, 6):
print(i)
Output:
2
3
4
5
Example 3: With Step
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
Use Cases:
- Repeating tasks a certain number of times
- Working with indexes
- Counting in intervals (like evens, odds, countdowns)
Summary Table:
Sequence Type | Example Value | Loop Example |
---|---|---|
String | "hello" |
for ch in "hello": |
List | ["a", "b", "c"] |
for item in ["a", "b", "c"]: |
Range | range(5) |
for i in range(5): |
Bonus Tips:
Use len(list) with range() for index-based loops:
for i in range(len(colors)):
print(colors[i])
- Use enumerate() to get both index and value
- Strings and lists are zero-indexed
List comprehensions (basic)
What Is a List Comprehension?
A list comprehension is a short and expressive way to create a new list by applying an operation to each item in an iterable, optionally filtering it with a condition.
Think of it as a one-liner for loops + append.
Basic Syntax:
new_list = [expression for item in iterable]
Optional condition:
new_list = [expression for item in iterable if condition]
Example 1: Squaring Numbers
Traditional for loop:
squares = []
for num in range(5):
squares.append(num ** 2)
List comprehension:
squares = [num ** 2 for num in range(5)]
Result:
[0, 1, 4, 9, 16]
Example 2: Filtering Even Numbers
evens = [num for num in range(10) if num % 2 == 0]
Result:
[0, 2, 4, 6, 8]
Example 3: Convert to Uppercase
words = [“hello”, “world”]
uppercase = [word.upper() for word in words]
Result:
[‘HELLO’, ‘WORLD’]
Example 4: Extract First Letters
names = [“Alice”, “Bob”, “Charlie”]
initials = [name[0] for name in names]
Result:
[‘A’, ‘B’, ‘C’]
Example 5: With Condition
scores = [75, 40, 88, 59, 90]
passed = [score for score in scores if score >= 60]
Result:
[75, 88, 90]
When to Use List Comprehensions
You want to:
- Transform each item in a list
- Filter items based on a condition
- Keep your code short and readable
Avoid if:
- Logic is too complex (use loops instead)
- Readability suffers
Summary Table:
Task | List Comprehension Example |
---|---|
Squares of 0–9 | [x**2 for x in range(10)] |
Only even numbers | [x for x in range(10) if x % 2 == 0] |
Convert to uppercase | [word.upper() for word in words] |
First letter of each name | [name[0] for name in names] |
Want to Level Up?
- Add if…else in expressions
- Use nested list comprehensions for 2D lists