5. Factorial



Hello!! So I wasn't sure how to do this problem, and I looked at the other forums and saw that the While loop is used. Just wondering why that is used instead of the for loop. Also, can I use the If-else statements for this problem? Would appreciate any help! Below is my current code:

Replace this line with your code. 
def factorial(x):
    for num in x:
        if num == 1:
            return 1


Hello @myoung05,

Maybe, because the while is easier? :wink:

That said, please, your code doesn't look complete -- The else block.

Complete that, and then we could see how help could come in.


For the else block, I was just planning on doing the following:

num= num*(num-1)
return num

My else portion is completely wrong :frowning: I know that I should be subtracting each number by 1, but I don't know how to replace the values.


Please describe what is happening to num in this construct. Are you expecting it to be a range from 1 to x? If so then specify that.

The direction we iterate is trivial since multiplication is commutative (can be multiplied in any order).

Will always return 1 when num is 1. This logic is unnecessary in the case of a range. That means the entire if statement is not needed.

To accumulate a product we need to start with a value of 1 and repeatedly multiple by the next number in the sequence.

result = 1
# set up the loop
    result *= num
return result

Factorial - was my approach too simple?

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