Menu
Coddy logo textTech

While Loop

Part of the Fundamentals section of Coddy's Python journey — lesson 36 of 77.

A while loop is different from the for loop. A for loop allows us to iterate over a specific range, whereas a while loop allows us to keep iterating as long as a certain condition is met.

To use a while loop write:

while condition:
	code

The code will execute only if the condition is True.

The condition is typically formed using comparison operators such as <= (less than or equal to), >= (greater than or equal to), < (less than), > (greater than), or == (equal to). The loop keeps running as long as that comparison evaluates to True, and stops as soon as it becomes False.

Inside the loop body, you usually need to update the variable being checked. This is done with augmented assignment operators like += (add and assign), -= (subtract and assign), *= (multiply and assign), or /= (divide and assign). For example, x *= 2 is a shorthand for x = x * 2. Without updating the variable, the condition would never change and the loop would run forever.

There are many use cases where a while would solve the problem, but the for loop would not.

For example consider this problem:

Find the smallest power of 2 that is greater than a given number.

To solve it we will use a while loop that will repeatedly multiply the current power of 2 by 2 until it becomes greater than the given number:

number = 27
power_of_two = 1

while power_of_two <= number:
    power_of_two *= 2

print(power_of_two)

Here, power_of_two <= number is the condition using a comparison operator, and power_of_two *= 2 updates the variable each iteration using an augmented assignment operator. Once power_of_two exceeds number, the condition becomes False and the loop stops.

challenge icon

Challenge

Beginner

Write a program that gets one input, float number.

Use a while loop to divide the input by 2 as long as the number is bigger or equal to 3.5.

Print the first number that is smaller than 3.5.

Cheat sheet

A while loop runs as long as a condition is True:

while condition:
    code

Use comparison operators to form the condition: ==, <, >, <=, >=.
Use augmented assignment operators to update the variable each iteration: +=, -=, *=, /=.

number = 27
power_of_two = 1

while power_of_two <= number:
    power_of_two *= 2  # update variable to avoid infinite loop

print(power_of_two)  # 32

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals