I am a beginner in python and I need some help with a case: I need to print pairs of numbers which are input from a for loop – for example
JavaScript
x
5
1
count_of_numbers = int(input())
2
3
for numbers in range(2*count_of_numbers):
4
number = int(input())
5
Let’s say we enter 3 2 1 4 5 0 4, I need to print the sum of the paired numbers – 3 + 2, 1 + 4 etc. Could anybody brighten me up with an idea on how exactly this is done?
Advertisement
Answer
I tried to keep much of your code:
JavaScript
1
8
1
count_of_numbers = int(input("Please enter the number of pairs: "))
2
3
for i in range(count_of_numbers):
4
number1 = int(input("Number 1 = "))
5
number2 = int(input("Number 2 = "))
6
print ("Sum of " + str(number1) + " and " + str(number2) + " = " +
7
str(number1 + number2))
8
I made a few changes:
- since the loop requests 2 inputs instead of one, the loop only runs up to
count_of_numbers
. I could have used “+ 1”, but preferred to start at zero, as the variablei
(formerlynumbers
) isn’t used. - In order to guide the user running this program, I’ve added some text to the
input()
calls