Yes. I know, the “fun/funnier/funniest” pun, It’s done, get over it.
Today’s practice is about factorials. In math, these are expressed as “n!” and the expression equivalent to it is n! = (n)*(n-1)*(n-2)… and so on, until 1. for example 3! = (3)(2)(1) = 6, 4! = (4)(3)(2)(1) = 24, and 5! = (5)(4)(3)(2)(1) = 120.
So… As you might expect, our code needs to take an input an produce it’s factorial as an output. We can do this with a loop… or recursively, and yes, I’ll go over both.
Factorial using loops is kind of the easy way and… It works best for your computer, let’s just say you’ll save your computer a lot of resources. Plus, we kind of already did this with loops, let’s open up wsq07, remove one of the limits and rename the other one as the user’s input, replace the initial value of c with 1 instead of 0, and inside the loop replace the addition with multiplication. Like this :
————————————————————————–
Editor :
Terminal :
————————————————————————–
Great! it works. What pass does is literally nothing, we just don’t want i to multiply c when it equals 0, range(1, a+1) would work as well. What if we want to use a while loop instead of a for?
Well, we’d have to use c as a counter instead of a printable variable and use the input variable as the printable variable :
————————————————————————–
Editor :
Terminal :
————————————————————————–
c -= 1 is the same as c = c -1. We use c > 1 as conditional instead of c > 0, because when c = 1, then the loop’s output would be 0.
Our time is now. Actually… not our time, it’s more like… recursion time. Python supports recursion, this