Write a python program to calculate the sum of digits in a given number.
Implement a program to calculate the sum of digits in a given number.
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
19-Jun-2023Sure, here is a Python program to calculate the sum of digits in a given number:
Python
This program works by first defining a function called
sum_of_digits(). This function takes a number as input and returns the sum of the digits in the number. The function works by first initializing a variable calledsum_of_digitsto 0. Then, it enters a while loop that continues as long as the number is greater than 0. Inside the while loop, the function gets the rightmost digit of the number and adds it to thesum_of_digitsvariable. Then, the function divides the number by 10 to remove the rightmost digit. The while loop continues until the number is 0. Finally, the function returns thesum_of_digitsvariable.The main function of the program simply gets the number from the user and then calls the
sum_of_digits()function to calculate the sum of the digits. The main function then prints the sum of the digits to the console.To run the program, you can save it as a Python file and then run it from the command line. For example, if you save the program as
sum_of_digits.py, you can run it by typing the following command into the command line:Code snippet
This will print the sum of the digits to the console.
Here is an example of the output of the program:
Code snippet
As you can see, the output of the program is the sum of the digits in the number 12345, which is 15.