Practice makes perfect: Factorial


It behaves properly. But i want to confirm that is it okay to write it like this. I know of recursive function but coding in this way, shouldn't be a problem, though it looks little bit like a javascript

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

print factorial(5)


Your code needs two more edits to become perfect:

  1. Rename total to product. Total sounds more like "sum" or "addition".
  2. Change for x in range(n+1): to for x in range(2, n+1):. Do you notice the difference? What could be the reason for starting at 2 and not 1 or 0?

Hope it helps :smiley:


Thanks for your help

def factorial(n):
    product = 1
    for x in range(2, n+1):
       product *= x
    return product

print factorial(5)


What about the questions I asked? Do you know the answers?


the range() starts from default 0 if start not mentioned and factorial of 0 and 1 is 1. To avoid it, we started the range from 2 and ended it on n+1. It not only gives us all the factorials and their results but also negates the need for an continue statement on x = 0.
Hope i am write moderator sir