在 Python 中返回外部函数错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14924820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:52:38  来源:igfitidea点击:

Return outside function error in Python

pythonfunction

提问by user2081078

This is the problem: Given the following program in Python, suppose that the user enters the number 4 from the keyboard. What will be the value returned?

这就是问题所在:给定以下 Python 程序,假设用户从键盘输入数字 4。返回的值是什么?

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    return counter

Yet I keep getting a outside function error when I run the system what am I doing wrong? Thanks!

然而,当我运行系统时,我不断收到外部函数错误,我做错了什么?谢谢!

回答by mgilson

You have a returnstatement that isn't in a function. Functions are started by the defkeyword:

您有一个return不在函数中的语句。函数由def关键字开始:

def function(argument):
    return "something"

print function("foo")  #prints "something"

returnhas no meaning outside of a function, and so python raises an error.

return在函数之外没有任何意义,因此 python 会引发错误。

回答by Rohit Jain

You can only return from inside a function and not from a loop.

您只能从函数内部返回,而不能从循环中返回。

It seems like your return should be outside the while loop, and your complete code should be inside a function.

似乎您的 return 应该在 while 循环之外,而您的完整代码应该在函数内。

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a returnat all. Just print the value of counteroutside the while loop.

如果这些代码不在函数内,那么您根本不需要 a return。只是打印的价值counter之外while loop

回答by Ike Ike

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

正如其他贡献者已经解释的那样,您可以打印出计数器,然后用 break 语句替换返回值。

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break

回答by Appyens

You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.

您没有在任何函数中编写代码,只能从函数返回。删除 return 语句并只打印您想要的值。