Factorial

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

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)

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

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

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

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

I understand how the factorial works but how do you know what number to enter? In Python 2 Lesson 8 part 2 of Loops, ‘Practice make Perfect’ we do the code as follows

def factorial(x):
total = 1
while x>0:
total *= x
x-=1
return total

print factorial(5)

So where does the 5 come from? Am I missing something?

Thanks in advance.

that could be any number you like to know the factorial of, you could even make it user input

1 Like

Of course, cool thank you.:slightly_smiling_face:
I have a habit of reading too far into things! lol :stuck_out_tongue:

No doubt I’ll be in touch again sometime soon.