Check for negatives in factorial function


#1

Hey, I'm trying to do a check for negative numbers with my factorial function so that it forces the user to enter a positive int. Below is what I tried, but when I call the function with say -23, I get:

Please provide a non-negative number: 3
>>>

Here's is the factorial function as I wrote it:

def factorial(x):
    total = 1
    if x == 0:
        return total
    elif x < 0:
        temp = int(raw_input('Please provide a non-negative number: '))
        factorial(temp)
    else:
        for i in range(1, x+1):
            total *= i
        return total

#2

Never mind. I got it to work by rewriting the elif loop as:

elif x < 0:
        temp = int(raw_input('Please provide a non-negative number: '))
        return factorial(temp)

#3

Are you trying to do a recursion? There are easier ways to do it, like by stating that factorial 1 equal 1. That way, python will think like this:

User: factorial of 4
Program: hmmmmmm.. thats 4 * 3!
but wait... 3! is 3*2!
but wait... 2! is 2*1!
Hey! I know 1! is 1...