I am trying to add all the digits of a positive integer. When I test out the number 434, the result was 4, instead of 11.
Here is what I have, I don't understand why is my code not going through all the digits of the number. How to correct it?
def digit_sum(x):
n=0
if x>0:
#get the end digit of the number,add to n
n+=x%10
#remove the end digit of the number
x=x//10
return n
Two main constructs of procedural programming are:
An if
statement is a selection statement. Since you want to add up all the digits in the number, your use of if
is inappropriate. In other words, using a selection statement will only give you the sum of the first digit you process (the final 4
in 434
).
Instead you should use an iteration statement like while
:
def digit_sum(number):
sumOfDigits = 0
while number > 0:
sumOfDigits += number % 10
number = number // 10
return sumOfDigits
You'll notice I've used more descriptive variable names. That's a good habit to get into because it self-documents your code.
You can also look into more Pythonic ways of doing this, such as:
def digit_sum(number):
return sum([int(digit) for digit in str(number)])
Whether that can be considered better is open for debate but it's a well-known way of writing Python succinctly.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments