Let's solve a simple Python problem using a while loop.
1. Can we count the number of digits in a given number?
Example:
num = 12345
Enter fullscreen mode
Exit fullscreen mode
Solution:
First, introduce a variable called count and initialize it to 0 .
num = 12345 count = 0 # Initial value is zero
while num != 0 : num = num // 10 # Removes the last digit count += 1
print ( "Number of digits:" , count )
Enter fullscreen mode
Exit fullscreen mode
Explanation:
num = num // 10 removes the last digit from the number.
count += 1 increases the count by 1.
The loop continues until the number becomes 0.
Output:
Number of digits: 5
Enter fullscreen mode
Exit fullscreen mode
That's it! We counted the total number of digits using a simple while loop without using any built-in functions.
2.β¦