Search code examples
pythonloopsfor-loopnumbersfactorial

How to find an EVEN number factorial in python?


So I have to define a function called def factorial_evens(num): and 'num' will be any number greater than 1. My problem is that I have to calculate a factorial of 'num' using only the even numbers in num.

So for example, if num = 6, then the factorial would equal 48 as opposed to 720.

My current code is only able to do regular factorials with even number inputs but will not do factorials with the even numbers in 'num'.

def factorial_evens(num):
    num = 6
    if num % 2 == 0:
        product = 1       
        for i in range(num):
            product = product * (i+1)
        print(product)

Solution

  • Your conditional was in the wrong place. This looks like what you tried, but should work.

    def factorial_evens(num):
         product = 1       
         for i in range(num):
             if (i % 2 == 1):
                 product = product * (i+1)
         print(product)
    

    It would be better to use a stride in the range declaration to save yourself some effort

    def factorial_evens(num):
        product = 1
        for i in range(2, num+1, 2):
            product *= i
        print(product)