[英]Passing variables between functions in Python
Ok so I am having a tough time getting my head around passing variables between functions:好的,所以我很难在函数之间传递变量:
I can't seem to find a clear example.我似乎找不到一个明确的例子。
I do not want to run funa() in funb().我不想在 funb() 中运行 funa()。
def funa():
name=input("what is your name?")
age=input("how old are you?")
return name, age
funa()
def funb(name, age):
print(name)
print(age)
funb()
Since funa
is returning the values for name and age, you need to assign those to local variables and then pass them into funb:由于funa
返回name 和 age 的值,您需要将它们分配给局部变量,然后将它们传递给 funb:
name, age = funa()
funb(name, age)
Note that the names within the function and outside are not linked;注意函数内部和外部的名称是没有链接的; this would work just as well:这也能正常工作:
foo, bar = funa()
funb(foo, bar)
Think of it as passing objects around by using variables and function parameters as references to those objects.将其视为通过使用变量和函数参数作为对这些对象的引用来传递对象。 When I updated your example, I also changed the names of the variables so that it is clear that the objects live in different variables in different namespaces.当我更新您的示例时,我还更改了变量的名称,以便很明显对象位于不同命名空间的不同变量中。
def funa():
name=input("what is your name?")
age=input("how old are you?")
return name, age # return objects in name, age
my_name, my_age = funa() # store returned name, age objects
# in global variables
def funb(some_name, some_age): # a function that takes name and
# age objects
print(some_name)
print(some_age)
funb(my_name, my_age) # use the name, age objects in the
# global variables to call the function
As it is returning a tuple, you can simply unpack it with *
:当它返回一个元组时,你可以简单地用*
解压它:
funb(*funa())
It should look something like this:它应该是这样的:
def funa():
# funa stuff
return name, age
def funb(name, age):
# funb stuff
print ()
funb(*funa())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.