JimmyStruthers
JimmyStruthers

Reputation: 37

Understanding factorials in Python

I know how to code a function for the factorial of a number but I am not sure why it works.

def factorial (num):
    ans = 1
    for i in range (1,num + 1):
        ans *= i
    return (ans) 

In my mind ans remains one and is multiplied by every index on 1 through nums + 1. So it would look like: (1 * 1, 1 * 2, 1 * 3,...). How does this function lead to the factorial of the number in the parameter?

Upvotes: 4

Views: 116

Answers (3)

Perplexabot
Perplexabot

Reputation: 1989

Why not introduce some print statements in your code to see what is going on?

def factorial(num):
    ans = 1
    for i in range(1, num + 1):
        print(f" ans = {ans}, going to multiply by {i}")
        ans *= i
    return ans


print("Trying to find the factorial of 5")
final = factorial(5)
print(f"Final answer is: {final}")

This gives:

Trying to find the factorial of 5
 ans = 1, going to multiply by 1
 ans = 1, going to multiply by 2
 ans = 2, going to multiply by 3
 ans = 6, going to multiply by 4
 ans = 24, going to multiply by 5
Final answer is: 120

So bottom line, you need to better understand what *= is doing in ans *= i (aka in-place operators), see here: https://docs.python.org/3/library/operator.html#in-place-operators

Upvotes: 4

Mureinik
Mureinik

Reputation: 311163

Note the usage of the *= operator - in each iteration of the loop ans is multiplied by i, and the result saved back to ans.

Let's look at the first couple of iterations:

  1. i=1 - ans * i is 1*1, or 1, which is saved back in ans.
  2. i=2 - ans * i is 1*2, or 2, which is saved back in ans.
  3. i=3 - ans * i is 2*3, or 6, which is saved back in ans. ... and so on.

Upvotes: 0

Pac0
Pac0

Reputation: 23149

a *= b means :

  1. take the content of a,
  2. multiply it by b,
  3. and store the result into a again.

(a in my example is ans for you)

So there is one variable, the same is used for every iteration. There is no list or such as you think it does, that takes the role of growing until the big final result.

ans starts at the value of 1, then will be multiplied by 2, and the result will replace it so it becomes 2, then will be multiply by 3, so it becomes 1 * 2 * 3 = 6, etc..

By the way, sometimes we call this kind of variable an "accumulator", in algorithmics.

Upvotes: 1

Related Questions