Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中的函数之间传递变量_Python - Fatal编程技术网

在Python中的函数之间传递变量

在Python中的函数之间传递变量,python,Python,好吧,我很难在函数之间传递变量: 我似乎找不到一个明确的例子 我不想在funb()中运行funa() 由于funa将返回name和age的值,因此需要将这些值分配给局部变量,然后将它们传递到funb: name, age = funa() funb(name, age) 请注意,函数内部和外部的名称没有链接;这同样有效: foo, bar = funa() funb(foo, bar) 可以将其视为通过使用变量和函数参数作为这些对象的引用来传递对象。当我更新您的示例时,我还更改了变量的名称,

好吧,我很难在函数之间传递变量:

我似乎找不到一个明确的例子

我不想在funb()中运行funa()


由于
funa
将返回name和age的值,因此需要将这些值分配给局部变量,然后将它们传递到funb:

name, age = funa()
funb(name, age)
请注意,函数内部和外部的名称没有链接;这同样有效:

foo, bar = funa()
funb(foo, bar)

可以将其视为通过使用变量和函数参数作为这些对象的引用来传递对象。当我更新您的示例时,我还更改了变量的名称,因此很明显,对象位于不同名称空间中的不同变量中

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

当它返回元组时,您只需使用
*
将其解包即可:

funb(*funa())
它应该是这样的:

def funa():
  # funa stuff
  return name, age

def funb(name, age):
  # funb stuff
  print ()

funb(*funa())

Daniel是对的,但这是你从阅读Python简介或变量和函数教程中学到的东西。那么为什么这样做比不使用全局变量更好呢?首先,因为你将依赖于在整个过程中使用的相同名称。谢谢,这很清楚,但我仍然不明白,如果名称和年龄最终都是全局的,为什么首先要使用函数,而不仅仅是使用全局变量?这取决于你的计划目标是什么。随着程序的增长,除非您封装数据,否则它将变得不可管理——这意味着避免使用全局变量。其他关注点是如何使用该函数。假设将来您希望维护name:age对的
dict
。现在,您的名称、年龄和全局变量是有问题的。您必须更改函数以及使用数据的所有位置。
def funa():
  # funa stuff
  return name, age

def funb(name, age):
  # funb stuff
  print ()

funb(*funa())