Factorial


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096#


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


#2

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.


#3

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.


#4

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
    else:
        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.


#5

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


#6

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.


#7

@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!


#8

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