While loops in Python (14/100 Days of Python)
A while loop is a type of control flow statement that allows you to execute a block of code repeatedly until a certain condition is met. The basic syntax for a while loop in Python includes a condition and a block of code that should be executed until the condition holds:
while condition:
# code to be executed while the condition is true
The code block indented under the while loop will be executed repeatedly as long as the condition
is true. Once the condition becomes false, the loop will exit and the program will continue with the next line of code after the loop.
Here is an example of a simple while loop that counts down from 10 and prints each number:
count = 10
while count > 0:
print(count)
count -= 1
This program would output all the numbers from 10 to 1:
10
9
8
7
6
5
4
3
2
1
It’s important to make sure that the condition in a while loop eventually becomes false, otherwise the loop will run indefinitely, which is known as an infinite loop. You can use the break
statement to exit a while loop early if a certain condition is met. For example:
count = 10
while True:
print(count)
count -= 1
if count == 0:
break
In this case, the loop will run until the count
variable becomes 0, at which point the break
statement will be executed and the loop will exit.
Working with number digits
While loops are especially useful when processing digits of a number as they allow you to continuously perform an operation on each digit until you have processed all of the digits. A great example is calculating the sum of the digits of a number:
n = int(input('Enter a number:'))
total = 0
while number > 0:
digit = n % 10 # Get the last digit of the number
total += digit # Add the digit to the sum
n //= 10 # Remove the last digit from the number
print('The sum of the digits is', total)
This while loop works by continuously dividing the number
by 10 and taking the remainder as the next digit to be processed. The loop continues until the number
becomes 0, at which point all of the digits have been processed.
Note that here the digits are processed from the last digit of a number to the first one. So, we technically process the number from the least significant digit to the most significant one. Can you get a new number from n
that would have the reversed value of n
?
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — while loops
- Full series: 100 Days of Python
- Previous topic: For loops
- Next topic: break and continue