Sum of digits of an input number in Python

Example 1

We read the input as string ( by default ) and as string is an iterable object we can find the each digit ( char as a string ) by using the position starting from 0 as first position.

In next step covert each char to integer by int() function and then add them all to get the sum of the digits.
my_sum of the digits of an input number in Python by using floor , reminder & by using string position

n=input("Enter a Number :")
my_sum=0
for i in range(0,len(n)):
    my_sum=my_sum+int(n[i])
print("Sum of digits in number : ", my_sum)
Output
Enter a Number :549
sum of digits in number :  18
In above code we used len() to get the number of elements ( or char here ) in the string object n.

Example 2

To any number if we divide by 10 then reminder will be the right most digit.
If 4534 is divided by 10 then reminder is 4 ( the right most digit ).
The floor ( or quotient ) value of 4534 after the division by 10 will be 453, so we can loop through and find the floor values till the floor value became 0. Inside the loop we can get reminders as digits of the number. Here is the code.
n=int(input("Enter a Number :"))
my_sum=0
while(n>0):
    i=n%10   # reminder value of division
    my_sum=my_sum+i
    n=n//10  # floor value of division
print("sum of digits in number=",my_sum)
Output
Enter a Number :1251
sum of digits in number=9

Using recursive function

n=int(input("Enter a Number :"))
total=0
def my_sum(n):
    global total
    if n<=0:
        return 0
    else:
        i=n%10   # reminder value of division
        total=total+i
        n=n//10  # floor value of division
        my_sum(n) # Using recursive function 
        return total
print("sum of digits in number = ",my_sum(n))
We are using recursive function here.
All Sample codes
Fibonacci series Factors of a number Factorial of a number Armstrong Number
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer