Skip to content Skip to sidebar Skip to footer

How Can I Read Multiple (variable Length) Arguments From User Input And Store In Variables And Pass It To Functions

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. Bel

Solution 1:

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]
>>>defadd(numbers):...returnsum(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:

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

Solution 2:

If you use *args it can take an arbitrary amount of positional arguments. You can make similar procedures for other operations.

defaddition(*args):
    returnsum(args)

calc = {
        '+':addition,
        #'-':subtraction,#'/':division,#'*':multiplication,
        }

defget_input():
    print('Please enter numbers with a space seperation...')
    values = input()
    listOfValues = [int(x) for x in values.split()]
    return listOfValues


val_list = get_input()

print(calc['+'](*val_list))

This is the way I would implement the calculator. Have a dictionary that holds the operations (I would use lambdas), then you can pass the list of numbers to the specific operation in the dictionary.

Post a Comment for "How Can I Read Multiple (variable Length) Arguments From User Input And Store In Variables And Pass It To Functions"