Joel Aqu.
Joel Aqu.

Reputation: 2459

New to Python, think I am using sum incorrectly?

input1 = raw_input("Hello enter a list of numbers to add up!")
lon = 0
while input1:
  input1 = raw_input("Enter numbers to add")
  lon = lon + input1
print lon

This program is supposed to add all the numbers given. It would not work so I tried making a list:

input1 = raw_input("Hello enter a list of numbers to add up!")
lon = []
while input1:
  input1 = raw_input("Enter numbers to add")
  lon.append(input1)
print sum(lon)

and it still would not work? Any solutions why? I'm a beginner to Python and have been doing it only for about a month. Thanks!

Upvotes: 0

Views: 148

Answers (3)

John La Rooy
John La Rooy

Reputation: 304473

It looks like maybe you want to terminate on an empty input, so you should check for that before trying to turn it into an int

print "Hello enter a list of numbers to add up!"
lon = 0
while True:
    input1 = raw_input("Enter numbers to add")
    if not input1:
        # empty string was entered
        break
    lon = lon + int(input1)
print lon

This program will crash if the user enters something that cannot be converted to an int, so you can add an exception handler like this

print "Hello enter a list of numbers to add up!"
lon = 0
while True:
    input1 = raw_input("Enter numbers to add")
    if not input1:
        # empty string was entered
        break
    try:
        lon = lon + int(input1)
    except ValueError:
        print "I could not convert that to an int"
print lon

Likewise in the second version of your program, you would need to do this

lon.append(int(input1))

You could add an exception handler similar to that shown above

Upvotes: 0

Guy Adini
Guy Adini

Reputation: 5504

First of all, I am assuming that your indentation is correct (tab/spaces for the statement inside the while loop) - otherwise, you should fix that.

In addition, raw_input returns a string. In the first example, you could replace it with "input", and it would work.

In the second example, you could split the string into numbers and apply sum to them, like so:

input1 = raw_input("Enter numbers to add")
lon.extend(map(int, input1.split()))

Note that I used "extend" and not append - otherwise, I would be adding the list of numbers as a list element inside the list, instead of extending it with new numbers.

Upvotes: 0

Tim Withers
Tim Withers

Reputation: 12069

input1= int(raw_input("Enter numbers to add"))

You must type cast it, as what you are entering is a string. That should fix the issue.

Or as Keith Randall, pointed out, use input("Enter numbers to add") instead.

Upvotes: 2

Related Questions