如何从用户输入读取多个(可变长度)参数并存储在变量中并将其传递给函数

时间:2017-07-02 12:34:54

标签: python python-2.7 function arguments

尝试创建一个计算器,它可以采用由空格分隔的可变长度的整数。我能够创建一个基本的计算器,可以读取两个参数并进行操作。以下是我想要实现的目标。

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

我不知道如何将这个int的varibale长度传递给函数,假设添加函数。我可以为两个变量做到这一点。

添加我所知道的:

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)

需要python专家帮助!!! 加(A,B)。不知道如何将多个args从输入读取到函数。

2 个答案:

答案 0 :(得分:2)

使用输入可以实现此目的:

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

split方法默认会在空格中拆分字符串,并创建这些项目的列表。

现在,如果你有更复杂的东西,如:

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

正如您所看到的,您正在按空格划分更长的数字序列。当你打电话给split时,你会看到你有一个数字列表,但表示为字符串。你需要有整数。因此,这是对map的调用将字符串键入整数的地方。由于map返回一个map对象,我们需要一个列表(因此调用map周围的列表)。现在我们有一个整数列表,我们新创建的add函数会得到一个数字列表,我们只需在其上调用sum即可。

如果我们想要一些需要更多工作的东西,比如减法,如建议的那样。让我们假设我们已经有了数字列表,以便让示例更小一些:

此外,为了使其更具可读性,我将逐步完成:

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

答案 1 :(得分:0)

如果使用* args,它可以采用任意数量的位置参数。您可以为其他操作制作类似的程序。

def addition(*args):
    return sum(args)

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

def get_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))

这是我实施计算器的方式。有一个包含操作的字典(我会使用lambdas),然后你可以将数字列表传递给字典中的特定操作。