Practical 8: Program to Enter a Number and Then Calculate the Sum of Its Digits.
Problem Statement
Write a Python program to calculate the sum of the digits of a given number.
The program should:
- Accept a number as input from the user.
- Calculate and print the sum of the digits of the number.
For example, if the user enters 1234, the program should calculate:
1 + 2 + 3 + 4 = 10
Solution Code
# Program to calculate the sum of digits of a number
# Input: Take a number from the user
num = int(input("Enter a number: "))
# Initialize sum of digits to 0
sum_of_digits = 0
# Loop to calculate sum of digits
while num > 0:
digit = num % 10 # Get the last digit
sum_of_digits += digit # Add the digit to the sum
num = num // 10 # Remove the last digit from the number
# Output the sum of digits
print(f"The sum of the digits is: {sum_of_digits}")
Output
- The program will ask the user to input a number.
- It will then calculate the sum of the digits of that number and print the result.
Example outputs for different inputs:
Enter a number: 370
370 is an Armstrong number.
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 2 Practical 8 solution where we have written Python Program to Enter a Number and Then Calculate the Sum of Its Digits.
- Input of Number:
- The program prompts the user to enter a number, which is then stored in the variable num.
- Sum of Digits Calculation:
- The program uses a while loop to iterate through the digits of the number.
- In each iteration:
- The last digit of the number is obtained using the modulus operator (num % 10).
- The last digit is added to the sum_of_digits variable.
- The last digit is removed from the number by using integer division (num // 10).
- This process repeats until the number becomes 0.
- Displaying the Result:
- After the loop completes, the sum of the digits is displayed using the print() function.
Key Concept Learned
- Extracting Digits Using Modulus and Integer Division:
- The program demonstrates how to extract digits from a number using the modulus (%) operator and remove the last digit using integer division (//). These are essential techniques for problems that require manipulating individual digits of a number.
- Looping through Digits:
- The while loop is used to repeatedly process each digit of the number, making it a key concept for problems involving digit manipulation.
- Accumulators:
- The program introduces the concept of an accumulator (in this case, the sum_of_digits variable) to keep track of the running total during the iteration process.