0% found this document useful (0 votes)
3 views10 pages

Python Loops Iterations Note

This document provides a comprehensive tutorial on Python loops and iterations, covering both for and while loops, their syntax, and usage. It explains key concepts such as the break and continue keywords, nested loops, the range function, and the enumerate function, along with practical examples. Additionally, it highlights common mistakes to avoid and key takeaways for effective loop usage in Python.

Uploaded by

geraldasiedu998
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views10 pages

Python Loops Iterations Note

This document provides a comprehensive tutorial on Python loops and iterations, covering both for and while loops, their syntax, and usage. It explains key concepts such as the break and continue keywords, nested loops, the range function, and the enumerate function, along with practical examples. Additionally, it highlights common mistakes to avoid and key takeaways for effective loop usage in Python.

Uploaded by

geraldasiedu998
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Loops and Iterations — Complete

Tutorial

(Corey Schafer — Python Tutorial for Beginners 7: Loops


and Iterations - For/While Loops)
1. What Are Loops?
Loops let you repeat code multiple times without writing it over and over. Instead of
writing print() 10 times, you write one loop that runs 10 times.
Two types of loops in Python:
• For Loop — loops through a sequence (list, string, range, etc.)
• While Loop — keeps running as long as a condition is True

2. For Loops
Basic For Loop — Looping Through a List:
Python
nums = [1, 2, 3, 4, 5]

for num in nums:


print(num)

# Output:
# 1
# 2
# 3
# 4
# 5

How it works: The variable num takes the value of each item in the list, one at a time. The
indented code runs once for each item.
Looping Through a String:
Python
for letter in 'Hello':
print(letter)

# Output:
# H
# e
# l
# l
# o

The break Keyword


break stops the loop completely and exits it:
Python
nums = [1, 2, 3, 4, 5]

for num in nums:


if num == 3:
print('Found!')
break
print(num)

# Output:
# 1
# 2
# Found!

The loop stops at 3 — it never prints 4 or 5.


The continue Keyword
continue skips the current iteration and moves to the next one:
Python
nums = [1, 2, 3, 4, 5]

for num in nums:


if num == 3:
print('Found!')
continue
print(num)
# Output:
# 1
# 2
# Found!
# 4
# 5

It skips printing 3 (the print(num) below continue doesn't run for 3), but the loop keeps
going.
Nested For Loops (Loop Inside a Loop)
Python
nums = [1, 2, 3]
letters = ['a', 'b', 'c']

for num in nums:


for letter in letters:
print(num, letter)

# Output:
# 1 a
# 1 b
# 1 c
# 2 a
# 2 b
# 2 c
# 3 a
# 3 b
# 3 c

How it works: For EACH number, the inner loop runs through ALL the letters. The inner
loop completes fully before the outer loop moves to the next item.
The range() Function
range() generates a sequence of numbers. Very useful with for loops:
Python
# range(stop) — starts at 0, goes up to (but not including) stop
for i in range(10):
print(i)
# Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

# range(start, stop)
for i in range(1, 11):
print(i)
# Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

# range(start, stop, step)


for i in range(0, 20, 2):
print(i)
# Output: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18

enumerate() — Get Index and Value


Python
courses = ['History', 'Math', 'Physics', 'CompSci']

for index, course in enumerate(courses):


print(index, course)

# Output:
# 0 History
# 1 Math
# 2 Physics
# 3 CompSci

Start counting from 1 instead of 0:


Python
for index, course in enumerate(courses, start=1):
print(index, course)

# Output:
# 1 History
# 2 Math
# 3 Physics
# 4 CompSci

3. While Loops
A while loop keeps running as long as the condition is True:
Python
x = 0

while x < 10:


print(x)
x += 1

# Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

How it works:
1. Check: is x < 10 ? Yes → run the code
2. Print x, then add 1 to x
3. Go back to step 1
4. When x reaches 10, the condition is False → loop stops
Infinite Loops (Be Careful!)
If the condition NEVER becomes False, the loop runs forever:
Python
# DON'T DO THIS (infinite loop):
x = 0
while x < 10:
print(x)
# Forgot to add x += 1, so x stays 0 forever!

Always make sure your while loop has a way to end.


break in While Loops
Python
x = 0

while True:
if x == 5:
break
print(x)
x += 1
# Output: 0, 1, 2, 3, 4

while True creates an infinite loop, but break stops it when x equals 5.

continue in While Loops


Python
x = 0

while x < 10:


x += 1
if x == 5:
continue
print(x)

# Output: 1, 2, 3, 4, 6, 7, 8, 9, 10
# (5 is skipped)

4. For Loop vs While Loop — When to Use Each


Use Case Best Loop
Loop through a list/sequence For loop
Loop a specific number of times For loop with range()
Loop until a condition changes While loop
Loop until user input stops it While loop
You know how many iterations For loop
You DON'T know how many iterations While loop

5. The else Clause in Loops


Python has a unique feature — you can add else to a loop. The else block runs ONLY if the
loop completes without hitting a break :
For loop with else:
Python
nums = [1, 2, 3, 4, 5]

for num in nums:


if num == 6:
print('Found 6!')
break
else:
print('6 was not found')

# Output: 6 was not found


# (because break was never triggered)

Python
nums = [1, 2, 3, 4, 5, 6]

for num in nums:


if num == 6:
print('Found 6!')
break
else:
print('6 was not found')

# Output: Found 6!
# (else doesn't run because break was triggered)

While loop with else:


Python
x = 0

while x < 5:
print(x)
x += 1
else:
print('Loop completed!')

# Output: 0, 1, 2, 3, 4, Loop completed!


6. Practical Examples
Example 1: Loop Through a List and Find Something
Python
clients = ['Restaurant A', 'Plumber B', 'Salon C', 'Clinic D']

for client in clients:


if client == 'Salon C':
print(f'Found client: {client}')
break
else:
print('Client not found')

# Output: Found client: Salon C

Example 2: Sum All Numbers in a List


Python
nums = [10, 20, 30, 40, 50]
total = 0

for num in nums:


total += num

print(f'Total: {total}')
# Output: Total: 150

Example 3: Simple Password Checker (While Loop)


Python
password = ''

while password != 'nexaflow':


password = input('Enter password: ')

print('Access granted!')

Example 4: Count Even and Odd Numbers


Python
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_count = 0
odd_count = 0

for num in nums:


if num % 2 == 0:
even_count += 1
else:
odd_count += 1

print(f'Even: {even_count}, Odd: {odd_count}')


# Output: Even: 5, Odd: 5

Example 5: Multiplication Table


Python
num = 7

for i in range(1, 11):


print(f'{num} x {i} = {num * i}')

# Output:
# 7 x 1 = 7
# 7 x 2 = 14
# 7 x 3 = 21
# ... etc

Example 6: Loop Through a Dictionary


Python
student = {'name': 'Gerald', 'age': 19, 'company': 'Nexaflow'}

for key, value in [Link]():


print(f'{key}: {value}')

# Output:
# name: Gerald
# age: 19
# company: Nexaflow
7. Common Mistakes to Avoid
1. Forgetting to increment in while loops → infinite loop
2. Off-by-one errors → range(10) gives 0-9, not 1-10
3. Modifying a list while looping through it → unexpected behavior
4. Indentation errors → code outside the loop runs only once
Python
# WRONG — modifying list while looping:
nums = [1, 2, 3, 4, 5]
for num in nums:
[Link](num) # Don't do this!

# RIGHT — create a copy:


nums = [1, 2, 3, 4, 5]
for num in [Link]():
[Link](num) # Safe

Key Takeaways
1. For loops = loop through sequences (lists, strings, ranges)
2. While loops = loop until a condition is False
3. break = stop the loop completely
4. continue = skip this iteration, go to the next
5. range() = generate numbers to loop through
6. enumerate() = get both index and value
7. else on loops = runs only if loop completes without break
8. Always ensure while loops can end — avoid infinite loops
Python Loops & Iterations Note | Add to Obsidian and practice each example in your Python
console.

You might also like