write a python program to find out the sum of digits of a given a number
- User
write a python program to find out the sum of digits of a given a number
- Assistant
Sure! Here's a Python program that finds the sum of the digits of a given number:
def sum_of_digits(number): sum = 0 while number > 0: digit = number % 10 sum += digit number //= 10 return sum # Test the program number = int(input("Enter a number: ")) result = sum_of_digits(number) print("Sum of the digits:", result)In this program, the function
sum_of_digitstakes a number as an argument and initializes a variablesumto store the sum of the digits. It then enters a while loop which continues as long asnumberis greater than 0.In each iteration of the loop, the last digit of
numberis extracted using the modulus operator%and stored in the variabledigit. The value ofdigitis added to the variablesum, andnumberis updated by removing the last digit using the floor division operator//.Once the while loop completes, the function returns the final sum of the digits.
To test the program, you can input a number and it will return the sum of its digits.