Programs often need to repeat a set of instructions. Manually coding instructions that repeat hundreds or even millions of times would be at best time-consuming and error-prone, or at worst impossible. Programmers may not even know how many times a set of instructions must be repeated!

To handle these situations, we use a ubiquitous programming language mechanism called loops. Here we’ll see two different types of loops: for loops, and while loops.

Loops, Setup

(for running code many times, in succession)

#while loop
while (condition):
	#your code here!
	#this runs while the condition is true
 
#for loop
for x in range(5):
	 #your code here!
	 #this runs 5 times
	 #x will be 0, 1, 2, 3, and 4

While Loops

While loops are in some ways, the simpler of the two. Notice that the structure of a while loop resembles another programming structure we’re already familiar with:

#IF STATEMENT
if(condition):
	#your code here!
	#this runs ONCE, if the condition is true
 
#WHILE LOOP
while(condition):
	#your code here!
	#this runs REPEATEDLY, only while the condition is true

When a while loop is encountered, the condition is checked. If it is true, the indented code is executed. This is exactly how an if statement works! However, with a loop the program will jump back to the condition, checking it again, and executing the indented code if the condition is still true. This process repeats until the condition finally evaluates to false.

This means we’ll almost always need to perform some action in the loop body that affects the loop’s condition, like so:

i = 10
while(i > 0):
	i = i-1
	print(f"Counter i is now at: {i}")

Result

The while loop above will run 10 times, printing out the value of the counter from 9 to 0, then ending

For Loops

For loops are slightly more difficult to set up, but offer some great benefits. We generally want to use a for loop when we have a set number of times we want to run our loop.

#for loop, this loop runs 10 times
for x in range(0, 10):
	 #your code here!

What’s going on above? We’re essentially saying “for each number in the range 0 to 9, run this loop”. Thus, we’ll run our loop 10 times.

But what is ‘x’? It is just a variable that holds an integer, and that integer corresponds to which loop we’re currently on. Think of it like a counter that keeps track of our current loop iteration. Each time through the loop, ‘x’ will grow bigger by 1. What if we did something like…

#for loop, this loop runs 10 times
for x in range(0, 10):
	 print(x)

Our result would be:

0
1
2
3
4
5
6
7
8
9

In English, our code is saying: “Go through all of the numbers from zero, all the way before 10. Each time we do so, run the indented code”.

We could also make our loop condition dependent on a variable, like so:

#Get user input as an integer
x = int(input())
for i in range(x):
	//this loop will run x times!

Result

The while loop above will run x times, if x is greater than 0. This is because the condition i < x will be true until i is equal to x. i starts at 0, goes up by 1 after each loop. and finally becomes x. When i is equal to x, the loop is finished.

A loop for every season

While loops and for loops are two different flavors of loop, but functionally they can do all of the same things. Which one you use for a particular problem depends on circumstance and preference. But there are some good rules of thumb to follow.

In general, a while loop is used when we’re not certain how many times the loop will run. For instance, many video games will run inside a while loop, and only exit the loop once the player has chosen to quit the game to return to the main menu. There is no way to know beforehand how long the player will be playing the game!

On the other hand, a for loop is more often used when you know how many times the loop will run (even if that number of iterations is stored in a variable). For example, the previous for loop is useful because we can immediately see that it will run x times, just by looking at the loop setup! If we had used a while loop, we would need to track down where i was being manipulated in the loop body, which could be after hundreds of lines of code! And the i counter variable must be created before the loop body, which means additional mental load for us as programmers.

So the rule of thumb would be: use while loops when you do NOT know how many times your loop will run, and use for loops when you DO know how many times your loop will run.

Loops, Examples

#while loop, this loop runs 10 times
i = 0
while(i < 10):
	#your code here!
	i = i+1
 
#for loop, this loop runs 10 times
for i in range(10):
	 #your code here!

Result

The while loop above will run 10 times. This is because the condition i < 10 will be true until i is equal to 10. i starts at 0, goes up by 1 after each loop. and finally becomes 10. When i is equal to 10, the loop is finished. The exact same logic applies to the for loop.

Infinite Loops, Examples

#Loop 1
while(True):
	print("This loop will run forever!")
 
#Loop 2
x = 10
while(x < 20):
	print("This loop will run forever")
 
#Loop 3
i = 100
for i in range(100, 50): 
	print("This loop will run forever")

Result

Loop 1: the condition is always true (because it is literally just the value true). Loop 2: the condition is always true because x is assigned the value 10, and the value of x never changes, so it will always be less than 20. Loop 3: the condition is always true because i is assigned the value of 100, and is increased by 1 each loop. i will always be greater than 50.

BELOW IS NOT IN PYTHON YET

Nested Loops

We can nest loops inside of each other, just like we can with if statements!

for(int j = 0; j < 3; ++j)
{
	for(int k = 0; k < 4; ++k)
	{
		Console.WriteLine("j is " + j + ", k is " + k);
	}
	Console.WriteLine("Inner loop finished, j is still " + j);
}

Output/Result

j is 0, k is 0
j is 0, k is 1
j is 0, k is 2
j is 0, k is 3
Inner loop finished, j is still 0
j is 1, k is 0
j is 1, k is 1
j is 1, k is 2
j is 1, k is 3
Inner loop finished, j is still 1
j is 2, k is 0
j is 2, k is 1
j is 2, k is 2
j is 2, k is 3
Inner loop finished, j is  still 2

The outter loop (which increments j) will run 3 times. The inner loop (which increments k) will run 4 times, on its own. Since the inner loop is inside of the outter loop, the inner loop will run 12 times (3 times 4).

WARNING

Copying/pasting loop initialization code carelessly can cause HUGE headaches. For example, can you spot the mistake below?

for(int i = 0; i < 3; ++i)
{
  for(int j = 0; j < 4; ++i)
  {
  	Console.WriteLine("Ooops, big mistake!);
  }
}

In the innermost loop, we’re incrementing i instead of j! This will mess up our loop structure, and our code will behave in strange ways. Ensure that you’re setting up your nested loops correctly!