Finding factorial of a number using function

Blog explain how to find a factorial of a number using function

This program make use of numpy module to find product of all elements in a list

Taking input from user in a main function and passing that value to a function find_factorial() which calculates factorial of a number. We have used try and except to inform user to enter only integer number

if __name__=='__main__':
    print('Enter any number to find the factorial')
    try:
        num = int(input('Enter Number : '))
        find_factorial(num)
    except ValueError:
        print('Please enter correct number')

Below function calculates factorial of a number. Function contain an empty list. This empty list is filled with values based on the number enter by user. At last using numpy function prod() to calculate product of all elements inside a list and printing the result

def find_factorial(num):
    num_list = []
    for n in range(1, num + 1):
        num_list.append(n)
    print(num_list)
    result = numpy.prod(num_list)
    print('Factorial of %d is %d' % (num, result))

Output

Enter any number to find the factorial
Enter Number : 4
[1, 2, 3, 4]
Factorial of 4 is 24

Complete Code

import numpy

def find_factorial(num):
    num_list = []
    for n in range(1, num + 1):
        num_list.append(n)
    print(num_list)
    result = numpy.prod(num_list)
    print('Factorial of %d is %d' % (num, result))

if __name__=='__main__':
    print('Enter any number to find the factorial')
    try:
        num = int(input('Enter Number : '))
        find_factorial(num)
    except ValueError:
        print('Please enter correct number')
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s