简体   繁体   English

在 Python 中返回外部函数错误

[英]Return outside function error in Python

This is the problem: Given the following program in Python, suppose that the user enters the number 4 from the keyboard.这就是问题所在:给定以下 Python 程序,假设用户从键盘输入数字 4。 What will be the value returned?返回的值是什么?

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!谢谢!

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 return at all.如果这些代码不在函数内,那么您根本不需要return Just print the value of counter outside the while loop .只需在while loop之外打印counter的值。

You have a return statement that isn't in a function.您有一个不在函数中的return语句。 Functions are started by the def keyword:函数由def关键字启动:

def function(argument):
    return "something"

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

return has no meaning outside of a function, and so python raises an error. return在函数之外没有任何意义,因此 python 会引发错误。

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 语句并只打印您想要的值。

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

它基本上发生在您从循环返回时,您只能从函数返回

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

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