Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Calculate the sum of digits of a number - Python Program

Example 1 :

# Sum of digits of a number n = int(input("Enter a number: ")) sum_digits = 0 temp = n while temp > 0: sum_digits += temp % 10 temp //= 10 print(f"Sum of digits of {n} = {sum_digits}")

Output

 
OUTPUT  :
Enter a number: 1234
Sum of digits of 1234 = 10 
 

Explanation

  • % 10 extracts the last digit.
  • // 10 removes the last digit.
  • Loop continues until temp becomes 0.
  • Complexity: O(d) where d = number of digits.