Search code examples
pythonsyntax-error

how to use return statement inside function as it's not working in script but works in interactive mode


I'm using python 3.7.2 shell in linux mint 32bit. when I run my def of factorial(as shown in code) it says that "" operator can't be apply for 'int' & 'nonetype' but i am using "" inside print function but that does no work. even though i am not able to use return statements inside function in script mode although it works in interactive mode. help me how can i use return statements inside function in script mode & please fix my factorial code so it works.

def factorial(n):
    if n == 0:
        results = print(1)
        return results
    else:
        x = factorial(n-1)
        result = print(n*x)
        return result

factorial(4)

the error that i get when using this is

File "/home/Location", line 12, in factorial
    result = print(n*x)
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

when i run in interactive mode it gave this error

SyntaxError: inconsistent use of tabs and spaces in indentation

I expect the factorial evaluation 4! = 24 but it gave the error shown 2nd code in script mode, and 3rd code error in interactive mode.


Solution

  • print(1) will return NoneType and hence when you do a recursive call, instead of 1, you are actually sending NoneType. Separate the assignment and print as shown below and your program works:

    def factorial(n):
        if n == 0:
            results = 1
            print(results)
            return results
        else:
            x = factorial(n-1)
            result = n*x
            print (result)
            return result
    
    factorial(4)