python - 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/
编辑:我修好了。事实证明,当从另一个函数传递值时,我们必须打破元组。谢谢大家。
解决方案
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
。但在此之前,您还需要声明res
为int
或任何其他人
寻找integer
价值
def add(values):
res=0
for val in values:
res+=int(val)
return res
推荐阅读
- python - Python 多处理:为什么使用 Process 从一开始就运行我的程序?
- c++ - 使用 http 发送管道的内容
- python - 错误:MissingPermissions 类型的对象不是 JSON 可序列化的
- python - 我列表中的最后一个值不会转换为整数
- javascript - 如何避免在javascript中从父类调用子方法?
- javascript - 如何使用laravel将chartjs图表生成为pdf?
- python - Jupyter 笔记本验证失败:键入字符串模式
- android - 我想在不打开应用程序的情况下实现共享 NFC 标签,例如从机场通过护照
- python - ConfigParserProperty 在 kivy 类中返回 val
- django - Celery - 收到“core.tasks.scrape_dev_to”类型的未注册任务