Python Loops
Note: This post is based on my old programming study notes when I taught myself.
while Loop
While loop will never stop the loop as long as the condition is True. Once the condition is False, the loop stops. If condition is always True, while loop becomes an infinite loop. To exit infinite loop in the IDE, press Ctrl+C.
Basic Syntax
while condition:
statement_1
statement_2
...
Important Note
When using while loop, it’s necessary to define the initial state of variables used in the condition.
cookie = 0
while cookie < 10:
cookie += 1
print('He ate %d cookie' % cookie)
if cookie == 10:
print("He ate all the cookies.")
How to escape from while loop?
Use break: If while loop reaches break, the loop will stop regardless of whether the condition is True or False.
chocolate = 10 # Initial state of chocolate variable
while True:
chocolate = chocolate - 1
print('We have %d chocolates left' % chocolate)
if chocolate == 0:
print("Chocolate Factory is shutting down. We don't have any chocolate left...")
break # Escape infinite loop
How to go back to condition of while loop?
Use continue:
num = 0 # initial number is set to zero
while num < 10:
num += 1 # num = num + 1
if num % 2 == 0:
continue
print(num)
# This will print:
# 1
# 3
# 5
# 7
# 9
Explanation:
num starts from 0 and as long as num is below 10, the loop operates and adds 1 to num variable. When num is an even number, it goes back to the original condition (num < 10) of while loop and continues operating.
for Loop
Basic Syntax
for variable in List/Tuple/String:
statement_1
statement_2
...
Examples
# Iterating through a list
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(f"I like {fruit}")
# Iterating through a string
word = "Python"
for letter in word:
print(letter)
continue in for loop
Like while loop, if for loop reaches continue, it will go back to the original condition of for loop and keep operating from there.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
# Output: 1, 2, 4, 5 (skips 3)
range() Function
Syntax
range(start, end, step)
By default, if we don’t set the start value and step value, Python automatically considers start=0 and step=1. range(n) means the range is from 0 to n-1.
Examples
# Basic range
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
# Range with start and end
for i in range(2, 8):
print(i) # Output: 2, 3, 4, 5, 6, 7
# Range with step
for i in range(0, 10, 2):
print(i) # Output: 0, 2, 4, 6, 8
Practical Example: Multiplication Table
# 9 x 9 multiplication table with for loop
for i in range(2, 10):
for j in range(1, 10):
print(i * j, end=" ")
print('') # New line after each row
# Result:
# 2 4 6 8 10 12 14 16 18
# 3 6 9 12 15 18 21 24 27
# 4 8 12 16 20 24 28 32 36
# 5 10 15 20 25 30 35 40 45
# 6 12 18 24 30 36 42 48 54
# 7 14 21 28 35 42 49 56 63
# 8 16 24 32 40 48 56 64 72
# 9 18 27 36 45 54 63 72 81
Various Usage of for Loop
Case 1: Add new elements to empty list
A = []
for _ in range(9): # from 0th index to 8th index, total 9
value = int(input("Enter a number: "))
A.append(value)
print(max(A))
Explanation:
_ in for loop is used when we don’t need to care about the iterator of for loop.
Case 2: List Comprehension
General case:
numbers = [1, 2, 3, 4]
result = [] # empty list
for num in numbers:
result.append(num * 3)
print(result) # [3, 6, 9, 12]
Using List Comprehension:
numbers = [1, 2, 3, 4]
result = [num * 3 for num in numbers]
print(result) # [3, 6, 9, 12]
More List Comprehension Examples
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Result: [0, 4, 16, 36, 64]
# With string operations
words = ['hello', 'world', 'python']
uppercase = [word.upper() for word in words]
# Result: ['HELLO', 'WORLD', 'PYTHON']
# Nested list comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
# Result: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
enumerate() Function
By using enumerate(), you can get a counter and the value from the iterable simultaneously. Basic syntax is to put an iterable object inside the parentheses of enumerate().
It returns tuple type (pair of index and element).
Example 1: Basic enumerate
numbers = [1, 2, 3, 4, 5, 6]
for n in enumerate(numbers):
print(n)
# Output:
# (0, 1)
# (1, 2)
# (2, 3)
# (3, 4)
# (4, 5)
# (5, 6)
Example 2: Unpacking enumerate
t = [1, 5, 7, 33, 39, 52]
for i, v in enumerate(t):
print("index: {}, value: {}".format(i, v))
# Output:
# index: 0, value: 1
# index: 1, value: 5
# index: 2, value: 7
# index: 3, value: 33
# index: 4, value: 39
# index: 5, value: 52
Example 3: enumerate with start parameter
fruits = ['apple', 'banana', 'orange']
for i, fruit in enumerate(fruits, start=1):
print(f"{i}. {fruit}")
# Output:
# 1. apple
# 2. banana
# 3. orange
Loop Control Summary
| Statement | Purpose | Usage |
|---|---|---|
break | Exit loop completely | Use when you want to stop the loop |
continue | Skip current iteration | Use when you want to skip to next iteration |
pass | Do nothing (placeholder) | Use as a placeholder for future code |
Examples
# break example
for i in range(10):
if i == 5:
break
print(i)
# Output: 0, 1, 2, 3, 4
# continue example
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0, 1, 3, 4
# pass example
for i in range(5):
if i == 2:
pass # Placeholder for branch-specific logic
print(i)
# Output: 0, 1, 2, 3, 4
Nested Loops
# Pattern printing
for i in range(5):
for j in range(i + 1):
print("*", end="")
print()
# Output:
# *
# **
# ***
# ****
# *****
Loop with else
Python loops can have an else clause that executes when the loop completes normally (not via break).
# for-else
for i in range(5):
print(i)
else:
print("Loop completed normally")
# while-else with break
numbers = [1, 2, 3, 4, 5]
target = 7
for num in numbers:
if num == target:
print(f"Found {target}")
break
else:
print(f"{target} not found in the list")
---