shivrk - 3 months ago 11

Python Question

Trying to create a calculator, which can take variable length of integers separated by space. I am able to create a basic calculator that would read two args and do operations. Below is what i am trying to achieve.

`select operation: Add`

Enter nos: 1 65 12 (this length can increase and any variable lenght of integers can be given)

I am not sure how would i pass this varibale length of int to functions, suppose addition function. I can do it for two variables.

Adding what i am aware of:

`x = input("enter operation to perform")`

a = input("1st no.")

b = input("2nd no.")

def add(a,b):

return a+b

if x == 1:

print add(a,b)

Need help from python experts!!!

Answer Source

Using input you can achieve this:

```
>>> result = input("enter your numbers ")
enter your numbers 4 5
>>> result
'4 5'
>>> a, b = result.split()
>>> a
'4'
>>> b
'5'
>>> int(a) + int(b)
9
```

The `split`

method will split your string by default on space and create a list of those items.

Now, if you had something more complicated like:

```
>>> result = input("enter your numbers ")
enter your numbers 4 5 6 7 8 3 4 5
>>> result
'4 5 6 7 8 3 4 5'
>>> numbers = result.split()
>>> numbers
['4', '5', '6', '7', '8', '3', '4', '5']
>>> numbers = list(map(int, numbers))
>>> numbers
[4, 5, 6, 7, 8, 3, 4, 5]
>>> def add(numbers):
... return sum(numbers)
...
>>> add(numbers)
42
```

As you can see you are taking a longer sequence of numbers split by space. When you call `split`

on it, you will see you have a list of numbers but represented as strings. You need to have integers. So, this is where the call to `map`

comes in to type the strings to integers. Since map returns a map object, we need a list (hence call to list around the map). Now we have a list of integers, and our newly created `add`

function takes a list of numbers, and we simply call `sum`

on it.

If we wanted something that required a little more work, like subtraction, as suggested. Let us assume we already have our list of numbers, to make the example smaller to look at:

Furthermore, to help make it more readable I will do it step by step:

```
>>> def sub(numbers):
... res = 0
... for n in numbers:
... res -= n
... return res
...
>>> sub([1, 2, 3, 4, 5, 6, 7])
-28
```