简体   繁体   English

python中递归函数的全局变量

[英]global variable for recursive functions in python

I am using pyhton to for a recursive function named sphereinput the function needs to return a variable name result as output.By declaring it as global in recursive function I wil not have to use return at the end of function. 我正在将pyhton用于名为sphereinput的递归函数,该函数需要返回变量名称结果作为输出。通过在递归函数中将其声明为全局变量,我将不必在函数末尾使用return。 Will the function return result having the correct answer when called in main file of my program. 在我程序的主文件中调用该函数时,返回的结果是否具有正确的答案。 My reservation is that for each call to the function sphereinput in itself the global variable result will be updated accordingly ,right? 我的保留意见是,对于每次对sphereinput函数本身的调用,全局变量结果都会相应地更新,对吗?

def sphereinput(parameters)
    global result
    Recursive call to sphereinput
    result=assigned value

Note that I did not use return statement here.Do I have to? 请注意,我这里没有使用return语句,必须这样做吗? Also when i define it in same file as main code after every call to function it starts executing the code lines below function again which are part of main code and must not be executed. 同样,当我在每次调用函数后在与主代码相同的文件中定义它时,它将再次开始执行函数下面的代码行,这些代码行是主代码的一部分,不能执行。

If i have to define this function in another file how do i call it from main file and then which variables will have to be defined global both in main and function code file? 如果必须在另一个文件中定义此函数,该如何从主文件中调用它,然后必须在全局和函数代码文件中全局定义哪些变量?

The result will be updated accordingly, but not returned unless you explicitly do so. 结果将相应更新,但除非您明确进行更新,否则不会返回。

I do not know what you mean with 我不知道你的意思

Also when i define it in same file as main code after every call to function it starts executing the code lines below function again which are part of main code and must not be executed. 同样,当我在每次调用函数后在与主代码相同的文件中定义它时,它将再次开始执行函数下面的代码行,这些代码行是主代码的一部分,不能执行。

To call it from main file you have to first import the module (=file) and then call its function: 要从主文件中调用它,您必须首先导入模块(= file),然后调用其函数:

import myfile
myfile.sphereinput(args)

You do not have to define the result variable anywhere else as long as you make sure that you don't use it before you call sphereinput. 您不必在其他任何地方定义结果变量,只要确保在调用sphereinput之前不使用它即可。

You can call your function recursively in another way as well, which does not require a global variable: 您也可以用另一种方式递归调用函数,该方法不需要全局变量:

while True:
  temp = sphereinput(args)
  if temp is None:
    break
  result = temp

Here you simply return None when you do not want any further recursions. 在这里,当您不希望进一步递归时,只需返回None即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM