5. Factorial


#1

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

File "python", line 8, in factorial
TypeError: list indices must be integers, not list

Okay so I get there is an easier way to do this but I want to validate the way I thought about how to do it. I'm calling on the specific values of my list which are integers but it's saying i'm calling on the list. Not sure how to fix it.

def factorial(x):
    l = [range(1,x+1)]
    print l
    count = x
    t = 1
    while count > 0:
        for n in l:
            t = l[n] * t
            count -= 1
        else:
            print t

#2

lets add a function call so we can see what is happening:

def factorial(x):
    l = [range(1,x+1)]
    print l
    count = x
    t = 1
    while count > 0:
        for n in l:
            t = l[n] * t
            count -= 1
        else:
            print t
print factorial(5)

l is a multi-dimensional, why? range() will simply give you a list, no need to nest a list in a list


#4

well, now that we have a function call, we can see the indexes you are requesting, you can simply add a print statement:

def factorial(x):
    l = range(1,x+1)
    print l
    count = x
    t = 1
    while count > 0:
        for n in l:
            print n
            t = l[n] * t
            count -= 1
        else:
            print t
print factorial(5)

Do you see a problem?


#5

Yes thank you. I am now getting a "IndexError: list index out of range" error.
I am very much a beginner thank you for help


#6

Figured it out!
I was calling on the list when I didn't need to

def factorial(x):
l = range(1,x+1)
print l
count = x
t = 1
while count > 0:
for n in l:
print
t = n * t
count -= 1
return t

print factorial(10)


#7

The forum is to help, not to provide you with the solution.

Now that we added a print statement, look at the indexes:

1
2
3
4
5

now, tell me, what indexes does your list have? Please answer my questions


#8

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