Gavin O'Doherty
Gavin O'Doherty

Reputation: 61

How do I calculate the sum of the individual digits of an integer and also print the original integer at the end?

I wish to create a Function in Python to calculate the sum of the individual digits of a given number passed to it as a parameter.

My code is as follows:

number = int(input("Enter a number: "))
sum = 0

while(number > 0):
    remainder = number % 10
    sum = sum + remainder
    number = number //10

print("The sum of the digits of the number ",number," is: ", sum)

This code works up until the last print command where I need to print the original number + the statement + the sum. The problem is that the original number changes to 0 every time (the sum is correct).

How do I calculate this but also show the original number in the print command?

Upvotes: 2

Views: 790

Answers (3)

theEpsilon
theEpsilon

Reputation: 1919

number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)

As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.

Upvotes: 1

VPfB
VPfB

Reputation: 17267

You can do it completely without a conversion to int:

ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)

It will compute garbage, it someone enters not a number

Upvotes: 1

Mushif Ali Nawaz
Mushif Ali Nawaz

Reputation: 3866

Keep another variable to store the original number.

number = int(input("Enter a number: "))
original = number
# rest of the code here

Another approach to solve it:

You don't have to parse the number into int, treat it as a str as returned from input() function. Then iterate each character (digit) and add them.

number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)

Upvotes: 2

Related Questions