What is the difference between a while loop and a for loop?
The main difference between a while loop and a for loop is how they decide when to stop. You use a for loop when you know exactly how many times you want to repeat a block of code, like iterating through a list of five items. You use a while loop when you want the code to keep repeating as long as a certain condition is true, even if you do not know how many times that will take.
Think of a for loop as running laps on a track: you plan in advance to run exactly four laps, and you count them off as you go. A while loop is like running on a treadmill until you feel tired: you do not know how many steps you will take beforehand, but you keep running as long as the condition 'I still have energy' remains true.
What is a for loop?
A for loop iterates over a known sequence or range. If you have a list of ten numbers, or you want to count from to , a for loop steps through each item one by one. The loop automatically updates its counter variable each time it runs. Because the sequence has a fixed size, the computer knows exactly when the loop will end before it even starts.
What is a while loop?
A while loop evaluates a true/false condition before every run. If the condition is true, the loop executes. If it is false, the loop stops. This is perfect for situations with unpredictable outcomes, like asking a user for a password. You want to keep prompting them 'while the password is incorrect'. The loop might run once, or it might run fifty times.
Where students slip: Infinite loops
The most common mistake with while loops is creating an infinite loop. In a for loop, the counting happens automatically. In a while loop, you usually have to manually update the variable being checked in the condition. If your condition is and you forget to add to inside the loop, will never reach . The loop will run forever, which will freeze your program.
Worked through
Write a program that prints the numbers , , and using both a for loop and a while loop.
Here is how you would do it in a language like Python.
Using a for loop:
for i in range(1, 4):
print(i)
Here, the range(1, 4) creates a sequence of numbers from up to (but not including) . The loop automatically assigns , then , then to the variable .
Using a while loop:
i = 1
while i < 4:
print(i)
i = i + 1
Here, we have to create the variable before the loop. The loop checks if . Inside the loop, after printing, we must manually add to . If we forget i = i + 1, the program will print forever.
Questions students ask
Ask about this topic
Where this comes from: OpenStax: Introduction to Python Programming · Khan Academy: Intro to Computer Science
See also