Why it isn't working?


Can anyone point out why this code is not working to solve factorial? I tryed it o IDLE and it is returning correctly. But not on Codecademy environment.

link to the excercise: https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096

Codecademy returns: Oops, try again.
factorial(3) returned 12 instead of 6

total = 1
def factorial(n):
    n = int(n)
    n = abs(n)
    global total
    if n == 0:
        return 1
    elif n == 1:
        return total
        total = total * n
        n = n - 1
        return factorial(n)


Hey there! I think this has something to do with using a global variable (and starting that variable at 1). Avoid using global variables inside functions as they can sometimes result in unexpected outcomes, because they can be changed elsewhere.

Try making this function without the use of a global variable.
And also, the if and else-statement for checking if n == 0 or n == 1 can be in one if.


Thanks, dutchc0de! I merged n==0 and n==1 in the same if, as you suggested. Still intrigued why this code don't work. But I thought of another way to solve the problem tha works properlly:

def factorial(x):
    x = int(x)
    x = abs(x)
    total = 1
    if x == 1 or x == 0:
        return 1
    while x > 1:
        total = total * x
        x = x - 1
    return total


Your previous use of return factorial(n) was good, see if you can find a solution using recursion like that.