'how to print the sum of all the inputs?
I wanted to take two numbers as an input 5 times and then print out all their sum. it would look like
enter two numbers:3 4
enter two numbers:3 5
enter two numbers:7 8
enter two numbers:7 1
enter two numbers:7 4
and an out put
7
8
15
8
11
Here is what i tried.
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
print(a+b)
My code prints out the sum for the last two inputs only.
Solution 1:[1]
The issue is that you are reassigning a
and b
during each iteration of the loop. Since you aren't storing the sum of a
and b
anywhere and when you move to the next iteration these values are updated to the latest inputs, there's no way to print them out. One easy fix is to append the sums to a list as you go and then print out the sums:
sums = []
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
sums.append(a+b)
for sum in sums:
print(sum)
Had you put the print(a+b)
statement within the loop, this would simply print the sums after each pair of inputs is entered and before the next inputs can be entered. In case you're wondering, the reason the final sum is actually printed is that Python continues to store the values of a
and b
even after the loop is over. This is not necessarily expected behavior, but it allows you to print a
and b
even when the loop has finished as Python still remembers the last values that were assigned to them.
Solution 2:[2]
Put the print statement inside of the scope of the for loop like so:
for k in range(5):
a,b=[int(a) for a in input("enter two numbers:").split()]
print(a+b)
Solution 3:[3]
for i in range(5):
a,b = input("enter two numbers:").split()
print(int(a)+int(b))
I think that code can help you what you need.split method converts a and b to string.So you need to convert them to integer value when you sum them.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jake Korman |
Solution 3 | CSS |