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
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)
Explanation:
-
num = num // 10removes the last digit from the number. -
count += 1increases the count by 1. - The loop continues until the number becomes 0.
Output:
Number of digits: 5
That's it! We counted the total number of digits using a simple while loop without using any built-in functions.
2. Can we solve the Sum of Digits?
Now, let's solve another problem using the same number.
Problem: Find the sum of all digits in a given number.
For example:
number = 12345
Expected output:
Sum of digits: 15
Step 1: Initialize a variable
Introduce a variable sum_of_digit to store the total sum.
sum_of_digit = 0
Step 2: Get the last digit
We already know that the modulus operator (%) returns the remainder.
When we use % 10, we get the last digit of the number.
12345 % 10 # 5
Step 3: Implement the logic
We can use the same while loop concept from the previous problem.
number = 12345
sum_of_digit = 0
while number != 0:
sum_of_digit += number % 10
number = number // 10
print("Sum of digits:", sum_of_digit)
How does the logic work?
-
number % 10extracts the last digit. -
sum_of_digit += number % 10adds the extracted digit to the total. -
number // 10removes the last digit.
This process continues until the number becomes 0.
Output:
Sum of digits: 15
Key Takeaway
We used two operators to solve this problem:
-
% 10– Extracts the last digit. -
// 10– Removes the last digit.
These two operations are useful for solving many number-based problems in Python.
Top comments (0)