Can someone explain how 24 is the result?

A simple step by step explaination would really help me understand. I have a learning disability so complex explainations dont help me.

def factorial(num):
   fact = 1
   while num > 0:
      fact = fact * num
      num = num -1
   return fact

print(factorial(4))


@ayanda so this function is just doing the same thing as the recursive function in the other post I answered, except using a loop instead of a recursive function. In this case:

  • We give the fact variable a starting value of 1
  • the loop starts to run, and will keep running until the num value is no longer bigger than 0
  • On each loop iteration, the fact value is set to fact's existing value, multiplied by the current value of num
  • num then has 1 subtracted from its value
  • When num's value gets to below 1, the loop stops running, and the final value of fact is returned.

So if we run factorial(4):

  • The starting value of num is 4, and the starting value of fact is 1.
  • After the first iteration of the loop, num is 3 (4 - 1) and fact is 4 (1 * 4).
  • After the second iteration of the loop, num is 2 (3 - 1) and fact is 12 (4 * 3).
  • After the third iteration of the loop, num is 1 (2 - 1) and fact is 24 (12 * 2).
  • After the fourth iteration of the loop, num is 0 (1 - 1) and fact is 24 (24 * 1).
  • The loop then stops running because num is no longer more than 0, and the final fact value of 24 is returned.
1 Like