Practice makes perfect: Factorial


#1



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

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:
            continue
        total *= x
    return total


print factorial(5)


#2

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:


#3

Thanks for your help

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


print factorial(5)

#4

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


#5

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