learnerX - 6 months ago 28

Python Question

So we are allowing a user to enter the number sets they want to enter. Each set of input will contain two integers separated by space. Then, the carriage return denotes the next set of inputs. For example,

`Enter number of sets: 3`

1 3

2 4

5 6

Next we input these in variables a,b, perform same operations, display 3 results:

`4`

3

1

It should first take all inputs

We have the logic of processing 1 set of input, but how do we loop it so that we can accept input in this format?

`sets = int(input("Enter number of sets: "))`

inputs = []

for n in range(sets):

inputs[n] = int(input().strip())

This crashes with list out of range error. We were thinking of creating a list of lists to hold the pair of values. Any easier solutions?

EDIT: What I'm looking for is a way to solve this problem. It doesn't have to be done via lists specifically. It is not a generic list out of range problem. I do understand what is going wrong, I just need another way to do it.

Answer

The `input()`

is returning a string like `"1 3"`

. Parse that string with something like, `a, b = map(int, input().split())`

. Save the output by using *list.append()*.

```
from pprint import pprint
inputs = []
results = []
sets = int(input("Enter number of sets: "))
for n in range(sets):
s = input()
a, b = map(int, s.split())
result = a + b
inputs.append([a, b])
results.append(result)
pprint(inputs)
pprint(results)
```

A sample session looks like this:

```
Enter number of sets: 3
1 3
2 4
5 6
[[1, 3], [2, 4], [5, 6]]
[4, 6, 11]
```

The learning points are:

- Use str.split() to convert a string like
`"1 3"`

into a list like`['1', '3']`

- Use
*map()*with*int()*to convert`['1', '3']`

to`[1, 3]`

- Use variable unpacking to extract the two values
- Use
*append()*to grow the*inputs*and*results*lists