Need Help With Factorials


#1

I’ve been having a bit of trouble writing my own code. I can read code pretty well but I’m not great at writing it. I thought that a “while” loop would work for my factorial but I keep getting the error “factorial(3) returned 3 instead of 6”. I would appreciate any help!

def factorial(x):
  total = 1
  while x > 0:
    total = x * total
    return total
    x -= 1

#2

your return statment is inside of your loop, which terminates it after a single iteration

put it beneath your while loop like so

def factorial(x):
  total = 1
  while x > 0:
    total = x * total
    x -= 1
  return total    

and it works as expected