5/15 problem with my program


#1

def factorial(x):
....if x==0 or x==1:
........fact=1
........return fact
....else:
........for i in range(1,x+1):
............fact*=i
............return fact

I get this error for the above program

Oops, try again. factorial(2) resulted in an error: local variable 'fact' referenced before assignment

how can i correct this program


#2

Hello designace84849,

I've found two points to modify your code:
1. in your else statement, you have to declare fact = 1, because otherwise you are doinig fact * i without knowing the value of fact
2. you have to return the fact not in your else statement

So that your code will look like this:

def factorial(x):
    if x==0 or x==1:
        fact=1
        return fact
    else:
        fact = 1
        for i in range(1, x+1):
            fact = i * fact
        return fact

There is also an alternative where you can use recursion.
This one is even shorter and you don't Need a Loop:

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

#3

You don't even need the else (for the recursive solution).


#4

How's that? :smiley: You always need an edge case when doing recursion! In this case it's 0.


#5

No ... I mean - the return can be out of the else. Sorry for not clarifying.