简体   繁体   中英

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?

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)
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM