5/15 factorial


#1

I am having trouble with all the exercises past lesson 4 in Practice Makes Perfect.
I am trying not to look at the answer. Here is my code.

def factorial(x):
  for n in str(x):
    n = int(n * (n - 1)) 
  return n
factorial(7)

I defined function name factorial and gave it argument int x. To my understanding from the last lesson you can not iterate an integer so I turned it to a string so I could use a for loop. Then I created a variable (n) and it turned n to int because you can’t do operations on a string. I’m getting all kinds of errors. Am I going in the right direction or am I totally out of the ball park. This is the error I am getting: Traceback (most recent call last):
File “python”, line 5, in
File “python”, line 3, in factorial
TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’


#2

I also am not understanding the hint: Have the function call itself.


#3

its the recursive solution, not the one i would recommend. Use a loop

why cast to string? lets see what happens when you do that:

for n in "7":
    print n

not really useful, it juts gives 7. You need all the values in range from 1 till x


#4

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