5. factorial


#1



I keep on getting the error message that "result" is referenced before assignment. But I thought I clearly assigned it, then referenced it. Help me out please.


def factorial(x):
    count = x - 1
    while count >= 1:
        result = x
        result *= count
        count -= 1
    return result


#2

I saw a cool solution in another post. There's a math function built in python called factorial. Basically we can use that.

def factorial(x):
from math import factorial
return factorial(x)


#3

When importing a module, you should import the module at the beginning of the program as it can cause some problems further down the line.


#5

You just want to move where you declare the 'result' variable to above the 'while' statement.


#7

In your code:

def factorial(x):
    count = x - 1
    while count >= 1:
        result = x
        result *= count
        count -= 1
    return result

you have defined result inside of the while loop. That means the result variable is only visible inside that loop and not outside it (this is called block-scoping). Now, the method tries to return result but since it is not visible outside the while loop, Python thinks that you haven't assigned any result variable yet (even though you technically have assigned, but it's in another scope so the return statement can't see it)

Hence, you need to define result inside of your method, like this:

def factorial(x):
    count = x - 1
    result = x

    while count >= 1:
        result *= count
        count -= 1
    return result

#8

Thank you! That makes much more sense!


#9

Quick and dirty:

import math

def factorial(x):
    return math.factorial(x)

#10

Good method! But remember that this exercise is about learning how to compute factorial (and learn its exact algorithm), rather than using built-in library methods :wink:


#11

This function returns 0 when we pass 0 instead of 1.


#12

Good observation! I had just fixed the code for the error the OP got and had not fixed the algorithm.

The fix is pretty simple:

  1. Store f as 1. This will be our answer. (Do you know why we are taking 1 not 0 as the initial value? :wink:)
  2. Loop from num to 1 as i.
  3. Multiply each i to f.

#16

You deserve two likes :grinning:


#18

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

I understand this much better!


#19