Finding factorial of a number using for loop

This blog include a program that finds factorial of a number

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

Ask user to input number to find the factorial

num = int(input('Enter a number to find factorial of a number: '))

Create empty list

num_list = []

Use append method inside for loop to add values into empty list(num_list)

for n in range(1,num+1):
num_list.append(n)

Display num_list

print(num_list)

Use numpy method to find the product of all elements in a list and assign output to a variable

result = numpy.prod(num_list)

At last, display the factorial value of a number entered by user

print('Factorial of %d is %d'%(num,result))

Output

Enter a number to find factorial of a number: 6
[1, 2, 3, 4, 5, 6]
Factorial of 6 is 720

Complete Code

import numpy
num = int(input('Enter a number to find factorial of a number: '))
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))
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