5. Factorial


#1



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


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


#2

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.


#3

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

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


#4

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?
#5

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