5. factorials


My factorial returns the wrong response... i took some time away from it to think about it and switched up the code but now i just have a problem returning the correct the response. I know i'm missing something small i just cant see it

# factorial(4) should be 4*3*2*1 etc.
def factorial(x):
    answer = 1
    while x >= 1:
        answer = answer * (x - 1)
        x -= 1
    return answer


I switched up from a if/else statement to a while statement.


It looks like you are trying to define a recursive function. If so, you don't need the while loop.

If x is 0, return 1. Else, return x * factorial(x - 1).

That's so simple :slight_smile:


see i had the if/else statement backwards in the first place it makes more sense thanks i knew it was something simple


If you want to achieve that with a while loop, consider this.

if x is 0 or 1, return 1.

If x is greater than 1, create a count variable and initialize it to 1.

While the count is less than or equal to x, multiply answer by count, and increment count by 1.

Return the answer.


Not really. I don't see that intention at all, especially since this course does not introduce recursion owing that it is hard to explain and understand, especially for beginners.


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

Change answer = answer * (x - 1) to answer = answer * x


Factorials are actually recursive functions and are best examined and interpreted that way. Consider establishing if x is less or equal to 1, if so, let it return 1. else return x factorial.


Except we do not offer any courses that introduce recursion, and factorial is not a good example since it grows so rapidly and uses a huge amount of memory. Stick to the iterative approach taught here.


[edit] code sample removed

What is everyone going on about recursive functions?


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