[英]Problem with calling a variable from one function into another
I am trying to call a variable from one function into another by using the command return
, without success. 我试图通过使用命令
return
将一个函数中的变量调用到另一个函数中,但没有成功。 This is the example code I have: 这是我的示例代码:
def G():
x = 2
y = 3
g = x*y
return g
def H():
r = 2*G(g)
print(r)
return r
H()
When I run the code i receive the following error NameError: name 'g' is not defined
当我运行代码时,我收到以下错误
NameError: name 'g' is not defined
Thanks in advance! 提前致谢!
Your function def G():
returns a variable. 您的函数
def G():
返回一个变量。 Therefore, when you call it, you assign a new variable for the returned variable. 因此,当您调用它时,您将为返回的变量分配一个新变量。
Therefore you could use the following code: 因此,您可以使用以下代码:
def H():
G = G()
r = 2*G
print (r)
You don't need to give this statement: 您无需给出以下声明:
return r
While you've accepted the answer above, I'd like to take the time to help you learn and clean up your code. 当您接受了以上答案后,我想抽出一些时间来帮助您学习和清理代码。
NameError: name 'g' is not defined
You're getting this error because g
is a local variable of the function G()
因为
g
是函数G()
的局部变量,所以出现此错误
Clean Version: 干净版本:
def multiple_two_numbers():
"""
Multiplies two numbers
Args:
none
Returns:
product : the result of multiplying two numbers
"""
x = 2
y = 3
product = x*y
return product
def main():
result = multiple_two_numbers()
answer = 2 * result
print(answer)
if __name__ == "__main__":
# execute only if run as a script
main()
Problems with your code: 您的代码有问题:
Have clear variable and method names. 有明确的变量和方法名称。
g
and G
can be quiet confusing to the reader. g
和G
可能会使读者感到困惑。
Your not using the if __name__ == "__main__":
您未使用
if __name__ == "__main__":
Your return in H()
unnecessary as well as the H()
function. 您在
H()
返回的结果以及H()
函数都是不必要的。
Use docstrings to help make your code more readable. 使用文档字符串可帮助提高代码的可读性。
Questions from the comments : 来自评论的问题 :
I have one question what if I had two or more variables in the first function but I only want to call one of them
我有一个问题,如果我在第一个函数中有两个或多个变量,但我只想调用其中一个,该怎么办?
Your function can have as many variables as you want. 您的函数可以具有任意多个变量。 If you want to return more than one variable you can use a dictionary(key,value) List, or Tuple.
如果要返回多个变量,则可以使用字典(键,值)列表或元组。 It all depends on your requirements.
这完全取决于您的要求。
Is it necessary to give different names,
a
andb
, to the new variables or can I use the samex
andg
?是否有必要给新变量使用不同的名称
a
和b
,或者我可以使用相同的x
和g
吗?
Absolutely! 绝对! Declaring another variable called
x
or y
will cause the previous declaration to be overwritten. 声明另一个名为
x
或y
变量将导致先前的声明被覆盖。 This could make it hard to debug and you and readers of your code will be frustrated. 这可能会使调试变得困难,并且您和您的代码阅读者会感到沮丧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.