algojedi
algojedi

Reputation: 67

recursively returning a ternary in python doesn't seem to work

the below code prints 1 but should print 24. rewriting with a simple if/else works fine.

def factorial(x):
  return 1 if (x == 1) else factorial(x - 1) 

print(factorial(4))

Upvotes: 0

Views: 57

Answers (1)

revliscano
revliscano

Reputation: 2272

It's not a ternary problem, but the definition of the function itself. This should be

def factorial(x):
  return x if x == 1 else x * factorial(x - 1)

Upvotes: 3

Related Questions