任意数量的用户输入功能

时间:2017-09-28 21:40:32

标签: python args

我创建了一个Python函数,它接受任意数量的整数输入并返回LCM。我想让用户以友好的方式向我传递任意数量的输入,然后让我的函数对它们进行评估。

我找到了一种合理的方法让用户一次一个地传递一些整数并将它们附加到列表中,但是,我似乎无法将我的函数作为列表或作为一个元组。

这是我的代码:

#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)

2 个答案:

答案 0 :(得分:2)

*args的想法是获取任意数量的参数并将它们视为易于处理的列表。

但是你只插入一个参数 - 一个列表。

使用lcm(*inputs)(将列表解压缩到不同的参数中)或仅将列表作为参数(意味着lcm仅定义为lcm(args))。

答案 1 :(得分:1)

您需要解压缩列表

result = lcm(*inputs)

但总的来说,我会说接受单个序列(listtuple等)参数而不是担心*arg解包会更加pythonic。