Colin Brochard
Colin Brochard

Reputation: 21

Arbitrary number of user inputs into function

I have created a Python function that takes an arbitrary number of integer inputs and returns the LCM. I want to ask the user to pass me an arbitrary number of inputs in a friendly way and then have my function evaluate them.

I have found a reasonable way to get the user to pass me some integers one at a time and append them to a list, however, I can't seem to get my function to process this either as a list or as a tuple.

Here is my code:

#Ask user for Inputs
inputs = []
while True:
    inp = input("This program returns the LCM, Enter an integer,\
    enter nothing after last integer to be evaluated: ")
    if inp == "":
        break
    inputs.append(int(inp))

#Define function that returns LCM
def lcm(*args):
    """ Returns the least common multiple of 'args' """
    #Initialize counter & condition
    counter = 1
    condition = False

    #While loop iterates until LCM condition is satisfied
    while condition == False :
        counter = counter + 1
        xcondition = []
        for x in args:
            xcondition.append(counter % x == 0)
        if False in xcondition:
            condition = False
        else:
            condition = True
    return counter

#Execute function on inputs
result = lcm(inputs)

#Print Result
print(result)

Upvotes: 2

Views: 1749

Answers (2)

Neo
Neo

Reputation: 3786

The idea of *args is to get an arbitrary number of parameters and treat them as a list for easy processing.

But you insert only one parameter - a list.

Either use lcm(*inputs) (which unpacks the list into different arguments) or just take a list as a parameter (meaning lcm is defined simply as lcm(args)).

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117856

You need to unpack your list

result = lcm(*inputs)

but in general I would say that it would be more pythonic to accepts a single sequence (list, tuple, etc) argument than to worry about *arg unpacking.

Upvotes: 1

Related Questions