首页 > 解决方案 > python:将多个变量从一个函数传递给另一个从用户提示

问题描述

python - 如何在python中将多个(2个或更多)变量从一个函数传递给另一个?我在互联网上进行了搜索,但我无法理解给出的大部分解释,许多示例不适合我的情况,我无法用 MRE 解决问题。这是示例代码:

def prompt_user():
    money1 = input("insert a value")
    money2 = input(" insert another value")
    return money1, money2

def add(money1, money2):
    cash = int(money1) + int(money2)
    return cash

two_values = prompt_user()
total = add(two_values)
print("you have "+ str(total))

这只是无法在python中完成吗?或者在这种情况下你是否必须使用类似列表的东西来传递参数?

我发现的示例(但不理解): Python — 传递多个参数 https://www.geeksforgeeks.org/how-to-pass-multiple-arguments-to-function/

编辑:我修好了。事实证明,当从另一个函数传递值时,我们必须打破元组。谢谢大家。

标签: pythonvariables

解决方案


def prompt_user():
    money1 = int(input("Insert a value: "))
    money2 = int(input("Insert another value: "))
    # You can get many more input like above
    
    return (money1, money2) # pass paratmeter inside () as tuple

def add(values):
    return sum(list(values))


multi_vaules = prompt_user()
total = add(multi_vaules)
print("you have "+ str(total))

如果您需要获取任何变量的总和,那么您可以按照代码进行操作

def prompt_user():
    money1 = input("Insert a value: ")
    money2 = input("Insert another value: ")
    # You can get many more input like above
    
    return (money1, money2) # pass paratmeter inside () as tuple

def add(values):
    res=''
    for val in values:
        res+=val
    return res

multi_vaules = prompt_user()

total = add(multi_vaules)
print("you have "+ str(total))

您可以自定义val是否需要int使用类型转换进行转换或浮动。如果您需要获取int类型,请使用int(val)获取res。但在此之前,您还需要声明resint或任何其他人

寻找integer价值

def add(values):
    res=0
    for val in values:
        res+=int(val)
    return res

推荐阅读