5. Factorial


#1

Can somebody explain why my method does not work. I used somebody else’s code to move on but I want to correct my mistakes.

I thought I could use a for loop to multiply the total each time by numbers of increment 1, starting from 1 and going to the number imputed. Then the elif was meant to handle the case if x was 1 or zero to begin with. I tried seeing what was going on with a print statement but It only ever gave me 0, 1, or none but I couldn’t understand why.


def factorial(x):
    total = 1
    if x > 1:
        for y in range(1, x + 1):
            total = total * y
            return total
    elif x == 1 or x == 0:
        return 1



#2

Hi @nortexg,

You have this statement as part of the for loop …

            return total

If the loop executes, because x > 1 is True, then that statement always executes during the first iteration of the loop. Remove one level of indentation, so that the statement is part of the if block, but no longer part of the for loop.


#3

Oh thank you it works now! I didn’t realize it would interact that way. Is their any scenario where you would want the if statement answer of True to execute or is that ALWAYS a mistake to put the return inside the for loop?


#4

For implementing some algorithms, it may be appropriate to have a for loop that contains a return statement. A possible place for such a pattern might be a function that determines whether or not a particular number is prime. Have you done the Practice Makes Perfect: is_prime exercise yet?


#5

Yeah I have, the indentations tripped me up again at first, here’s the code I used to solve it:
def is_prime(x):
if x < 2:
return False
elif x == 2 or x == 3:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
else: return True


#6