### Thread: Help calculate sum of digits

Page 1 of 2 12 Last
1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
6
Rep Power
0

#### Help calculate sum of digits

Code:
```n = eval (input ("Enter a number between 0 and 1000:"))
sumOfDigits = (n % 10) + (n // 10)

print ("The sum of the digits is" ,sumOfDigits )```
Hi everyone! Newbie here. I am stuck on getting the calculation right. The output when given 932, shows 95 instead of 14. And I just can't figure out the correct code to do this. Would appreciate any help!
2. Code:
```\$ python -c 'n = 932; print(n % 10, n // 10)'
2 93```
3. I would recommend making your input a string (or even leaving it a string). Then initialize a sum variable and iterate over the string with "+=int(i)":

Code:
```sumvar=0
strvar="{0:d}".format(inputnum)
for i in strvar: sumvar+=int(i)```
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
6
Rep Power
0
thanks for your replies rrashikin, b49P23TIvg! rrashikin, the requirement for this exercise is as follows: Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. (Hint: Use the % operator to extract digits, and use the // operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 // 10 = 93.)

From my code, I don't know how to properly add the digits to say 9+5=14.. I am getting the sum of 95.
5. Firstly, rrashkin's excellent program adds the digits one by one. It works for numbers with ten million digits!

Secondly, from my post you were supposed to figure out that

932%10 gives 2, which is the units digit, GOOD!

and that

932//10 gives 93, which is useful but incomplete because the 10s digit isn't zero. Which we'll generalize to "iterate until the number you're working with is reduced to zero".
6. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
6
Rep Power
0
Originally Posted by b49P23TIvg
Firstly, rrashkin's excellent program adds the digits one by one. It works for numbers with ten million digits!

Secondly, from my post you were supposed to figure out that

932%10 gives 2, which is the units digit, GOOD!

and that

932//10 gives 93, which is useful but incomplete because the 10s digit isn't zero. Which we'll generalize to "iterate until the number you're working with is reduced to zero".
I should add that I am absolutely new to python and this is just my second week in class.. and already I am feeling a little overwhelmed.... I understand about the % and // operators, but is there anyway you can modify my original code to show what I need to add/corrected? When I use str intead of eval/int, I am getting an error "Can't convert 'int' object to str implicitly"...
7. You need a loop, as in rrashkin's code. Here's a working modification of your program. If you don't know what divmod does then you can either try the manual or in the interpreter
>>> help(divmod)
And if you don't understand tuple assignment you'll need to read the entire python tutorial---a good idea anyway. That can be found at the prior link.

Code:
```n = eval (input ("Enter a number between 0 and 1000:"))

(quotient, remainder,) = divmod(n, 10)

sumOfDigits = remainder

while quotient:   # same as  while quotient != 0:
(quotient, remainder,) = divmod(quotient, 10)
sumOfDigits += remainder

print ("The sum of the digits is" ,sumOfDigits )```

Verification with executable Iverson notation
Code:
```   +/ 10 #.inv 932
14```
8. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
6
Rep Power
0
Originally Posted by b49P23TIvg
You need a loop, as in rrashkin's code. Here's a working modification of your program. If you don't know what divmod does then you can either try the manual or in the interpreter
>>> help(divmod)
And if you don't understand tuple assignment you'll need to read the entire python tutorial---a good idea anyway. That can be found at the prior link.

Code:
```n = eval (input ("Enter a number between 0 and 1000:"))

(quotient, remainder,) = divmod(n, 10)

sumOfDigits = remainder

while quotient:   # same as  while quotient != 0:
(quotient, remainder,) = divmod(quotient, 10)
sumOfDigits += remainder

print ("The sum of the digits is" ,sumOfDigits )```

Verification with executable Iverson notation
Code:
```   +/ 10 #.inv 932
14```
b49P23TIvg, really appreciate your reply! I have yet to run it, I am looking at it but I don't see the % and // operators in the code, it is required in the exercise to use them... my class is introduction to python, i feel like the commands you have might be too advanced... anyway you can dumb it down? for example, I don't think we've covered divmod yet... i really apologize if I'm almost demanding! it's just that i've looked everywhere and couldnt find what i need to get it to work...
9. Did you look at the divmod manual as b49P23TIvg suggested?
In here you can read that:
For integers, the result is the same as (a // b, a % b)
.

If you really want to show those operation, to calculate the quotient and remainder manually, you can do that.
10. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
6
Rep Power
0
Originally Posted by MrFujin
.

If you really want to show those operation, to calculate the quotient and remainder manually, you can do that.
Can you please show me how to include these operations manually within my code? ,
11. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2012
Posts
194
Rep Power
2
Well it has pretty much been spelled out for you, so I won't supply the code. But I'll try spelling it out again.

n%10 gets the current digit in the ones place (add this to a variable total every time through the loop)

n//10 strips one digit off of n (do this every time through the loop after the previous step).

Loop until n == 0.

That's it.

-Mek
12. Perhaps this program will confuse you. It's somewhat similar with regard to fearlessly assigning values computed by actual expressions to variables in a loop.
Code:
```print('')
print('Display Fibonacci numbers less than 100.')
print('')
print('\tThe first two Fibonacci numbers are 0 and 1.')#which we'll pretend we computed
print('\tThe next Fibonacci number is the sum of the')
print('\t2 most recently computed Fibonacci numbers.')
print('')

a = 0
b = 1
while b < 100:
print('{:2d}'.format(a)) # fancy code to right justify the output in field width of 2 for display
new_Fibonacci_number = a + b
a = b
b = new_Fibonacci_number```
13. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2014
Posts
6
Rep Power
0
Originally Posted by Mekire
Well it has pretty much been spelled out for you, so I won't supply the code. But I'll try spelling it out again.

n%10 gets the current digit in the ones place (add this to a variable total every time through the loop)

n//10 strips one digit off of n (do this every time through the loop after the previous step).

Loop until n == 0.

That's it.

-Mek
Not sure if I am getting my point across that I am just starting out.. so please don't assume that I should know something that is apparently so very obvious.. I GET the logic, I just don't know how to apply it. So seeing a working program (with the required conditions in the exercise) will make me better understand how it works. I know there are a thousand ways to do a task (and b49P23TIvg's code works obviously, but I am looking for a particular way to do it AND actually see it in the code and not just say "yeah you can put that in manually if you want but i'm not going to show you"... like really? anyways, i found what i was looking for:

Code:
```#  Read a number
number = eval(input("Enter an integer between 0 and 1000: "))

lastDigit = number % 10
remainingNumber = number // 10
secondLastDigit = remainingNumber % 10

remainingNumber = remainingNumber // 10
thirdLastDigit = remainingNumber % 10

# Obtain the sum of all digits
sum = lastDigit + secondLastDigit + thirdLastDigit

# Display results
print("The sum of all digits in " + str(number) + " is " + str(sum))```
14. OK, in future I'll be more sympathetic to those who claim "new programmer". You do have a class, did you attend? You have an instructor. Are there no python examples? Do you know how to run the interpreter interactively? Was

>>> help(divmod)

rrashkin was gentle, since rrashkin could have written
Code:
`\$ python -c "print('sum of digits:',sum(int(d)for d in input('Enter a number: ')))"`
Last edited by b49P23TIvg; February 11th, 2014 at 04:15 PM.
15. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
May 2013
Location
/dev/null
Posts
163
Rep Power
19
Originally Posted by pcorp1
anyways, i found what i was looking for
For now, yes; but when you are writing programs, you might want to keep in mind an important principle of software design - scalability. Your program might work for a 3 digit number. Wouldn't it be better if you could write a function that is more flexible; complete with validation checks. Heck, even your instructor would give you a straight A if you do all that
Page 1 of 2 12 Last