-1

I am trying to build a program which calculates the factorial of number num1. The question is: how can I multiply all the digits in i?

Here I have used a for loop for generating numbers backward from 5: 5,4,3,2,1,0

But is there any way I can multiply all the digits of the variable i?

for i in range(0,5,-1):
    print(i)

The result was as follows:

5
4
3
2
1

Is there any way I can get the product of the numbers. I expect the output to be 120.

glhr
  • 4,439
  • 1
  • 15
  • 26
Tanay Kumar
  • 81
  • 1
  • 2
  • 7

2 Answers2

0

Your for-loop is wrong.

range(start, end, step): to get all numbers from 5 down to 1, you need range(5, 0, -1)

You can accumulate the result in a variable within the loop. Start with 1 since that's the multiplicative identity.

retval = 1
for i in range(5, 0, -1):
    retval *= i
print(retval)
rdas
  • 20,604
  • 6
  • 33
  • 46
0

Note that you can easily compute the product of items in a list using reduce:

>> from functools import reduce
>> numbers = list(range(5,0,-1))
[5, 4, 3, 2, 1]
>> reduce((lambda x, y: x * y), numbers)
120
glhr
  • 4,439
  • 1
  • 15
  • 26