0

I'm fairly new to programming and after learning loops in python I tried making my version of a function that gives me the factorial of the number entered. I know one way is to do it by using recursion but I've been trying to use only loops for the same. The problem is that the code I've managed to come up with doesn't multiply the results of each iteration. Here's the code:

def myfactorial(k):
    t = 1
    while t<=(k-1):
        print(k*(k-t))
        t = t+1


myfactorial(7)

and here's the output: 42 35 28 21 14 7

thanks :)

  • You are only printing `k*(k-1)`, `k*(k-2)`, ..., `k*1`, not `k*(k-1)*(k-2)*...1`. You need to build up the product. Something like `t = 1; while k >0: t *= k; k-=1`. – chepner Oct 27 '21 at 16:29
  • 1
    A `for` loop would be simpler: `r = k; for t in range(1, k): r *= t` – chepner Oct 27 '21 at 16:30
  • you have to assing result to some variable instead of print it. And in next loop you have to use this variable to continue calculations. OR put values on list and later use other `for`-loop to calculate final result. – furas Oct 28 '21 at 09:33

0 Answers0