Factorial


#1

Hi,
I am working on lesson 5 on practice makes perfect and it’s solution is written below.

def factorial(x):

    total = 1 
    while x>0:
        total *= x
         x-=1
    return total
I have two doubts:
  1. Can I use while x >=1instead ofwhile x >0 ?
  2. What is the need of total *= x in the code ?
THANK YOU

#2

sure, why not? I prefer greater then zero, find it easier to read for this specific purpose

its a shorthand for:

total = total * x

its a critical part to make the program work (to calculate the factorial)


#3

Sorry for writing the topic which has does not support my query.
what is the need of total *= x in the code ?


#4

there is a difference between need and understanding. Do you understand what the line of code does?


#5

I do understand the difference between these two words.
What is the reason of typing that piece of code?How is this going to help?What is going to happen if I don’t type that code?

Thank-you


#6

its where the multiplication happens:

def factorial(x):

    total = 1 
    while x>0:
        print total, x, total * x
        total *= x
         x-=1
    return total

print factorial(6)

this should show you how the multiplication is happening and how total is increased