Loops

🔁 Loops let you repeat actions in your code.

1 for Loops

Use for loops to iterate over items in a sequence like a list or range.

for i in range(5):
    print(i)
0
1
2
3
4
math_subjects = ["Linear Algebra", "Calculus", "Probability"]
for subject in math_subjects:
    print(subject)
Linear Algebra
Calculus
Probability
math_subject = "Calculus"
for character in math_subject:
    print(character)
C
a
l
c
u
l
u
s
math_grades = {"Linear Algebra": 95, "Calculus": 90}
for subject in math_grades.keys():
    print(subject)
    for grade in math_grades.values():
        print(grade)
Linear Algebra
95
90
Calculus
95
90
math_grades = {"Linear Algebra": 95, "Calculus": 90}
for subject, grade in math_grades.items():
    print(subject, grade)
Linear Algebra 95
Calculus 90

2 Comprehensions: Lists and Dictionaries

Directly create a list or dictionary using a for loop.

countdown = [i for i in range(3,0,-1)]
print(countdown)
[3, 2, 1]
countdown = {"i"*i:i for i in range(3,0,-1)}
print(countdown)
{'iii': 3, 'ii': 2, 'i': 1}

3 while Loops

Use while loops when you want to repeat something until a condition becomes False.

courses_left = 10
while courses_left != 0:
    print("Still a student!")
    courses_left -= 1
Still a student!
Still a student!
Still a student!
Still a student!
Still a student!
Still a student!
Still a student!
Still a student!
Still a student!
Still a student!

4 break

break exits the loop immediately.

math_subjects = ["Linear Algebra", "Calculus", "Probability", "Statistics", "Graph Theory", "Discrete Math"]
for subject in math_subjects:
    if subject == 'Probability':
        print("No more math for me! Thank you 😊")
        break
No more math for me! Thank you 😊

5 continue

continue skips the rest of the current loop iteration and moves on to the next.

math_subjects = ["Linear Algebra", "Calculus", "Probability", "Statistics", "Graph Theory", "Discrete Math"]
for subject in math_subjects:
    if subject == 'Probability':
        continue
    print("😔")    
😔
😔
😔
😔
😔

6 Looping with enumerate()

Use enumerate() to get both index and item while looping.

math_subjects = ["Linear Algebra", "Calculus", "Probability"]
for i, subject in enumerate(math_subjects):
    print(i, subject)
0 Linear Algebra
1 Calculus
2 Probability

7 Looping with zip()

Use zip() to loop over two or more sequences at once.

math_subjects = ["Linear Algebra", "Calculus"]
math_grades = [95, 90]

for math_subject, math_grade in zip(math_subjects, math_grades):
    print(math_subject, math_grade)
Linear Algebra 95
Calculus 90

8 Infinite Loop Danger

If the while condition is never False, the loop will run forever.

# WARNING: This loop runs forever unless manually stopped
# while True:
#     print("Infinite loop!")

Common Errors

Some frequent errors encountered when dealing with Loops in Python.

for i in range(5)
    print(i)  
  Cell In[14], line 1
    for i in range(5)
                     ^
SyntaxError: expected ':'
while x < 5:
print(x)  
  Cell In[15], line 2
    print(x)
    ^
IndentationError: expected an indented block after 'while' statement on line 1