Start learning free

LESSON 146 OF 673 · WHILE LOOPS & FOR LOOPS

While loop in Python

Lesson

A while allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while condition:
	instruction1
	instruction2
	...

Let's check an example:

counter = 1

while counter <= 4:
	print("I made a mistake")
	counter += 1
	
print("Finished!")

The code that goes inside a while loop has to be indented! In this code, the first unindented line print("Finished!") marks the end of the while loop's body.

And so this program prints:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable counter = 1

1. First iteration:
	a. Is counter <= 4 true? <=> Is 1 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 2
	
2. Second iteration:
	a. Is counter <= 4 true? <=> Is 2 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 3
	
3. Third iteration:
	a. Is counter <= 4 true? <=> Is 3 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 4
	
4. Forth iteration:
	a. Is counter <= 4 true? <=> Is 4 <= 4 true? Yes. 
	b. print("I made a mistake") => Output: "I made a mistake"
	c. counter += 1 => counter = 5

5. Fifth iteration:
	a. Is counter <= 4 true? <=> Is 5 <= 4 true? No.
	b. Exit the loop.
	
6. print("Finished!") => Output: Finished!

Pro Tip:

A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check