Skip to content
Advertisement

Factorial function using lambda

I am trying to implement the function below into one line of lambda code.

def fac(num):
    num = int(num)
    if num > 1:
        return num * fac(num - 1)
    else:
        return 1

I have constructed a lambda statement, but I keep getting syntax error:

z = lambda z: if (z > 1) z * (z-1) else 1

Advertisement

Answer

First of all, you can’t refer to a global name z when there is a local variable (the parameter) by the same name.

Thus, we will declare a lambda statement called func and use the ternary operator in the good way.

func = lambda z: z * func(z-1) if (z > 1) else 1

Output

> func(5)
120
Advertisement