How do I print the sum of all of my numbers on CodeHS 8.4.5: Five Numbers?

Question:

Using a for loop, ask the user for five numbers. Store those numbers in a list. Each time you add a new number to your list, print the list. (Your list will initially be empty.)

You should report the sum of the numbers in the list at the end.

An example run of your program might look like this:

Number: 3
[3]
Number: 6
[3, 6]
Number: 12
[3, 6, 12]
Number: 2
[3, 6, 12, 2]
Number: -5
[3, 6, 12, 2, -5]
Sum: 18

This is my code right now:

my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print my_list
print "Sum: " + new_number*5

I almost have this code right. There’s just one problem: I need to print the sum. Right now, it’s an error because I have a str and int object on line 6 and I need that fixed.

This is the error that it gives:

Error: Line 6
TypeError: cannot concatenate 'str' and 'int' objects on line 6
Asked By: Logan Holmes

||

Answers:

my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print (my_list)
b= sum(my_list)
c=str(b)
print ("Sum: " + c)

Your code missed:
brackets in line 5 for printing
getting the sum for the list
converting sum to string for final concatenation before printing in last line

Answered By: J Patel
my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print my_list
print("Sum: " + str(sum(my_list)))

I replaced your last line in the code with the one in my previous comment, seems to be working fine, in both cases positive and negative numbers

here is another way to do it,

sum = 0
for i in range(5):
    sum += int(input("Number: "))
print("Sum: " + str(sum))

Hope this helps!

It is just this.

num = 0
for i in range(5):
    new_number = int(input("Number: "))
    num+=new_number
    print num

Not that hard.

Answered By: user13690085
my_list = []
for i in range(5):
    new_number = int(input("Number: "))
    my_list.append(new_number)
    print(my_list)
sum=my_list[0]+my_list[1]+my_list[2]+my_list[3]+my_list[4]
print ("Sum: " + str(sum))
Answered By: EGG
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.