在Python中返回外部函数错误

use*_*078 2 python function

这就是问题:在Python中给出以下程序,假设用户从键盘输入数字4.返回的价值是多少?

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

但是当我运行系统时,我一直遇到外部函数错误我做错了什么?谢谢!

Roh*_*ain 6

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

看起来您的返回应该在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()
Run Code Online (Sandbox Code Playgroud)

如果这些代码不在函数内部,那么根本不需要return.只需打印counter外面的值while loop.


mgi*_*son 5

您有一个return不在函数中的语句。函数由关键字启动def

def function(argument):
    return "something"

print function("foo")  #prints "something"
Run Code Online (Sandbox Code Playgroud)

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


App*_*ens 5

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