5

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!

user2081078
  • 51
  • 1
  • 1
  • 3
  • Possible duplicate of [Python return statement error " 'return' outside function"](http://stackoverflow.com/questions/7842120/python-return-statement-error-return-outside-function) – tripleee Sep 14 '16 at 14:49

5 Answers5

7

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
5

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
5

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.

Appyens
  • 129
  • 1
  • 7
1

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
Ike Ike
  • 11
  • 3
  • 1
    try not to repeat others' answer – godot Feb 07 '18 at 10:16
  • @Godot How is this a repetition. I acknowledge the previous answers and suggested a break statement to be used in the while loop. – Ike Ike Feb 07 '18 at 11:08
  • It doesn't change logic. If other answers are in functions and if you just extract them outside a function and don't change anything, no one would be consider your answer as helpful. – godot Feb 07 '18 at 11:14
  • and also question is about returning value and you doesn't have any 'returns' in your answer – godot Feb 07 '18 at 11:18
0

It basically occours when you return from a loop you can only return from function