Computer Science Researcher • Educator • Programming Instructor
Loops allow your program to repeat actions automatically. Instead of writing the same line many times, you can use a loop to perform the task efficiently. Python provides two main types of loops: while loops and for loops.
A while loop repeats as long as its condition is true. You must update the variable inside the loop; otherwise, it will run forever.
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
The loop continues because i <= 5 is true.
Each time the loop runs, i increases by 1.
A for loop repeats a block of code a specific number of times.
It is commonly used with range() or with lists.
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
range(1, 6) generates numbers 1 to 5.
The loop runs once for each value.
You can use a for loop to process each item inside a list.
fruits = ["apple", "banana", "mango"]
for item in fruits:
print(item)
Output:
apple
banana
mango
1. Which loop runs while a condition is true?
for2. What does range(1, 4) produce?
1, 2, 3, 43. Which loop is best for going through list items?
for4. What will this code print?
for i in range(3):
print("Hi")
Hi5. What must change inside a while loop to avoid an infinite loop?
The print statement