Factorial


#1



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


Oops, try again. factorial(2) returned 0 instead of 2


Trying to understand the logic. Can anyone help? I want to really understand what I'm doing wrong here.


def factorial(x):
    if x == 1 or x == 0:
        return 1
    total= 0
    for n in range(x+1):
        total *= n
    return total


#2

its not that hard:

0 * anything = 0


#3

Also range(x+1) will start at 0 so for x = 3 you'll have n = [0, 1, 2, 3] so you have to define another starting point.

Something that help me is to print out what I'm doing (so you could append n in a list and see what you get)


#4

replace total = 0 with total = 1


#5

Initialize total to 1, then:

if x == 0:
    return 1
else:
    for n in range(1, x+1):
        total *= n

#6

def factorial(x):
if x == 1 or x == 0:
return 1
total= 1
for n in range(1,x+1):
total *= n
return total

Sorry didn't care much for the first short response so I figured out shortly after. Main issue was the range and setting the correct index. I knew the total variable was set wrong but until i fixed the range it would not have mattered. Thanks


#7

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