Write a Python Program to Find The Sum of Digits of a Given Number Eg Sum of Number 123 Will be 6

Given a number message input to the Python program your task is to to separate all the digits present in the number and  find the sum of all the digits and print it.

This can be done using  python while loop

 

Write a Python Program to Find The Sum of Digits of a Given Number Eg Sum of Number 123 Will be 6

 

 


Write a Python Program to Find The Sum of Digits of a Given Number Eg Sum of Number 123 Will be 6

Let's take a variable number,  ask a user to enter a number using the input function call and then convert it into an integer using the int() function call type conversion.

Once we get a number, take another temporary variable temp and copy the contents of the number  e into the temporary variable.  also take another variable total and write the value of the total variable to 0. This variable total is used to store the sum of all the digits of the number.


number = int(input("Enter a Number : "))
temp = number
total = 0




Use the while loop to get all the digits of the number, perform the modulus addition and division (MAD)  on the temp number. Once you get the digits of the number added to the total as shown below.


while temp != 0:
   last_digit = temp % 10
   total = total + last_digit
   temp = temp // 10




Once the while loop completes the total will store the sum of all the digits of the given input number.  So using the print function call prints the total variable.

print(f"Sum of all digits of number {number} is : {total}")





Write a Python Program to Find The Sum of Digits of a Given Number
=====================================
number = int(input("Enter a Number : "))
temp = number
total = 0

while temp != 0:
   last_digit = temp % 10
   total = total + last_digit
   temp = temp // 10

print(f"Sum of all digits of number {number} is : {total}")






Output of the program
===========================

Enter a Number : 123
Sum of all digits of number 123 is : 6





Output 2
=====================

Enter a Number : 321
Sum of all digits of number 321 is : 6



Output 3
================

Enter a Number : 998993
Sum of all digits of number 998993 is : 47




Conclusion
=====================

Execute the above program by providing the random number as a input value to the Python program.  

Comment down below  if you have any suggestions to improve the above problem

Post a Comment

0 Comments