5. Factorial


#1

Why does it matter if I define a = 1 outside the While loop? When I put a = 1 after the while I get the message "factorial (2) returned 1 instead of 2"

def factorial(x):
    if x == 1:
        return 1
    else:
        a = 1
        while x > 0:
            a *= x
            x -= 1
            if x == 0: 
                return a


#2

because then a gets re-assigned with value of 1 in each iteration of the loop


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.