Loops (for · while)
for vs while at a Glance
| Feature | for | while |
|---|---|---|
| Number of repetitions | Fixed | Not fixed |
| When to use | Iterating over lists, range | Repeating while checking a condition |
| Syntax | for item in list: | while condition: |
| Example | Print every element of a list | Repeat 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
# strawberryExample 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 5Example 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: AThe 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
| Concept | Summary |
|---|---|
| for | Repeat a fixed number of times → iterate over a list |
| while | Repeat while checking a condition → repeat until input is received |
Reference: personal Notion study notes (onboarding course)
