Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 653
user2081078 Avatar asked Feb 17 '13 18:02

user2081078


1 Answers

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.

like image 147
Rohit Jain Avatar answered Sep 25 '22 21:09

Rohit Jain