Return outside function error in Python

2020-06-22 19:58发布

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?

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!

4条回答
Bombasti
2楼-- · 2020-06-22 20:03

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.

查看更多
劳资没心,怎么记你
3楼-- · 2020-06-22 20:22

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.

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. Just print the value of counter outside the while loop.

查看更多
何必那么认真
4楼-- · 2020-06-22 20:23

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

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1
    print(counter)
    break
查看更多
乱世女痞
5楼-- · 2020-06-22 20:26

You have a return statement that isn't in a function. Functions are started by the def keyword:

def function(argument):
    return "something"

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

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

查看更多
登录 后发表回答