Skip to content

Loops (for · while) ​

for vs while at a Glance ​

Featureforwhile
Number of repetitionsFixedNot fixed
When to useIterating over lists, rangeRepeating while checking a condition
Syntaxfor item in list:while condition:
ExamplePrint every element of a listRepeat until input is received

The for Loop ​

Definition: A statement that runs code repeatedly a fixed number of times

Features

  • Used when the number of repetitions is known
  • Useful for iterating over lists, strings and so on

Example 1: looping over a list

python
fruits = ["apple", "banana", "strawberry"]

for fruit in fruits:
    print(fruit)

# output:
# apple
# banana
# strawberry

Example 2: using range()

python
# range(5) = 0, 1, 2, 3, 4
for i in range(5):
    print(i)

# output: 0 1 2 3 4

# range(1, 6) = 1, 2, 3, 4, 5
for i in range(1, 6):
    print(i)

# output: 1 2 3 4 5

Example 3: looping over a dictionary

python
student = {"name": "Jo", "age": 25, "grade": "A"}

for key in student:
    print(f"{key}: {student[key]}")

# output:
# name: Jo
# age: 25
# grade: A

The while Loop ​

Definition: A statement that runs code repeatedly while a condition is true

Features

  • Used when the number of repetitions is not fixed
  • Keeps repeating until the condition becomes false
  • Watch out for infinite loops
python
count = 0

while count < 5:
    print(count)
    count += 1

# output: 0 1 2 3 4

# Repeat until input is received
while True:
    answer = input("Do you want to quit? (yes/no): ")
    if answer == "yes":
        break  # end the loop
    else:
        print("Continuing")

Summary ​

ConceptSummary
forRepeat a fixed number of times → iterate over a list
whileRepeat while checking a condition → repeat until input is received

Reference: personal Notion study notes (onboarding course)