Help

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Apr 1 20:00:30 EDT 2013


On Mon, 01 Apr 2013 14:44:45 -0700, khaosyt wrote:

> If I wanted to get the sum of some numbers (for example: 1 + 2 + 3 + 4 +
> 5 = 15) from the attached program what do I do? Keep in mind that the
> print statement prints the integers individually.


Yes, we know what the print statement does. Some of us have been using 
Python for weeks now.


Some comments interspersed within your code below:



> integer = 0
> denom = 10
> again = "y" #sentinel:

Technically, that's not a sentinel.

> while again == "y" or again == "Y":
>     integer = input("Enter a positive integer: ")

I believe that the last time you asked this question, you were told not 
to use the "input" function as it was dangerous or can lead to hard-to-
understand bugs. Change the above line to:

    integer = raw_input("Enter a positive integer: ")


Notice that if you do this, the so-called "integer" is actually a string. 
This is a good thing! You want it as a string, since that makes it easy 
to extract individual digits.


>     while denom <= integer:
>         denom = denom*10
>     while denom > 1:
>         denom = denom/10
>         number = integer/denom
>         integer = integer%denom
>         print str(number)

All this stuff with denom seems to be aimed at extracting the digits from 
a number. There's an easier way: just work with the string.

After the line I suggested above 

    integer = raw_input("Enter a positive integer: ")


"integer" is a string of digits. So you can iterate over the digits using 
a for-loop:

# this is not what you want!
for digit in integer:
    print digit


Instead of printing the digits, you want to add them up. So start by 
initialising a total, then add them:

    total = 0
    for digit in integer:
        total = total + digit


Warning! The above three lines contains a bug. If you make the changes I 
suggest, and try it, you will get an error. That's okay. Read the error. 
Try to understand what it is telling you. Hint: remember that total is an 
actual int, a number, while each digit is a single character, a string.

You need to convert each digit into a number before adding it. Hint: the 
int function takes a string, and converts it to a number.

py> 42 + "23"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
py> 42 + int("23")
65


This should hopefully give you enough information to get some working 
code. Try to write as much of the code as you can, and come back with any 
further questions *after* making a good effort.

Another hint: try experimenting at the interactive interpreter, or IDLE. 
If you're unsure about something, try it and see what happens *before* 
asking.


Good luck.




-- 
Steven



More information about the Python-list mailing list