Hello, all. I'm getting the following error on my code and have not been able to troubleshoot. Can anyone lend some guidance? Thanks!

Oops, try again. factorial(1) returned None, did you remember to return the result?

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


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

A loop ends the moment a return key is reached. Furthermore, instead of using a while loop, consider using an if/else statement... especially since your current function does not work if x is equal to 1.


In a while, you must modify the value of "x" by yourself. You're not modifying it. You can also try:
For x in range(1,n)

Then you don't need to worry about modifying the value.


Why would you loop through x like this:

def factorial(x):
    for x in range(1, n):
        num = x * factorial(x - 1)
    return num

When you could simply define an if/else statement like so:

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

Using a for loop feels not only unnecessary, but a tad bit excessive given the task for this exercise. But, to each his own, I guess.


Sorry, I hadn't noticed that it's possible to make factorial a recursive function. It's a nicer job...


It's okay. I mean, the way you are doing it is is completely fine. I just found it a bit excessive for newer learners.


@humbertova, @aquaphoenix 17,

Thank you both for helping. I didn't have a good enough understanding of
recursive functions, but now I see that they serve the same purpose as what
I was trying to accomplish with a loop. Thanks!


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