Factorial, HELP!


For this challenge, can i take the range(x) and multiply numbers in range together? If i can do that, how can i accomplish it?

Replace this line with your code.


You can use a loop :slight_smile: .


def factorial(x):
for a in range(x): # every number in that is in range
a = a * a

something like that?


You have the right idea. Now...what is a? You didn't define it.
Also, your function returns nothing right now.


a is the number in the range of numbers. And yes im going to return a


The thing is....you can't assign an index variable (a in your case) to something else. It's an index and is different from just a variable because the loop uses it to keep track of when to stop:

a = a * a

You're current function won't work properly:

print factorial(1)
print factorial(2)
print factorial(3)
print factorial(4)

>> 0
>> 1
>> 4
>> 9

Your range(x) function won't be going to the last number. For example: range(5) will only go to 4 as it excludes 5.


i have just found out theres a equation for factorial.
i got to admit the instructions for this challenge is confusing.

def factorial(x):
  if x == 1 or x == 0:
       return x
       return x * factorial( x - 1)


That's a recursive way of doing it and is sort of "out of scope" to what you have learned. I really encourage you to translate this to a loop form. To help you understand it a little better in terms of logic.

You were very close with doing the loop way which is better than that recursive way.

They want you to create a function that does factorials. You can search how to do it manually (math). These are challenges to help stretch your mind and help you problem solve like programmers. The easiest way is to know how to do things manually and then program the process.


Thanks for your help, im going to try and convert it into a loop form


Ok, i don't know how what to assign a to.


Uuhh...a is your index variable in your loop......
You need another variable in order to store your calculation in....
If you did the digit_sum practice, you'll see that you used a variable called total or something to add things into. And it started out as total = 0 before the loop.

Almost the same concept here. Except your initiating value is different....


Ok, i understand. Should it be outside the for loop or inside the for loop. After that can i do the if x == 0 or x == 1: in the for loop?


If x==1 or x==0 should be outside and before the loop. Your function will look a little like the recursive function except the last line will become your loop chunk.

As for a, it's used as an index variable in your loop so of course it should be inside the loop!


if range(4) only goes up to 3 how do i include the last number?


Buddy, if range(4) only goes up to 3...then range(5) goes up to 4... and then range(6) goes up to 5.
Do you see a pattern here?


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