Python

Basics of Python : Calculate Factorial

Basics of Python : Calculate Factorial

Python

 

Python is popular and easy to use language. It is widely used in data science, machine learning, Internet of Things (IoT)  and field of automation  However, it is necessary to learn basics to manipulate statements and customize programs.
In this post, I will make a simple factorial program which will illustrate concept of loop and function in Python.

To calculate factorial program  is given below


import numpy as np
def factorial(n):
fact=1
for i in np.arange(1,n+1):
fact=fact * i
return f
fact=factorial(5)
print(“Factorial of the number is”,fact)


Output of the program would be
Factorial of the number is 120

Statement “import numpy as np” import numpy library of python for arange function.
Statement “def factorial(n):” defines a function of name factorial which has a single parameter n.
Statement “fact=1” initializes the variable fact having value is equal to 1.
Statement “for i in np.arange(1,n+1):” has used arange(start, end) function of numpy which generates number from 1 to n.
Statement “fact=fact * i” is the most important statement to calculate factorial.
See the execution of the statement for n=5
if i=1 then fact= 1*1 then fact=1
if i=2 then fact= 1*2 then fact=2
if i=3 then fact= 2*3 then fact=6
if i=4 then fact= 6*4 then fact=24
if i=5 then fact= 24*5 then fact=120

Important Note about Indentation

Indentation ( Horizontal space before statement) is very important in Python, using indentation Python determines the scope of a statement.
Further, you can observe in program that after “def factorial(n):” statement fact=1 is declared with a horizontal space. Otherwise, python interpreter will throw an error ” Indentation is requires at line number…..”.

So, be careful about indentation in  programming during program making.

Conclusion-

Learning basics of Python is key point to customize and make your own program. You have to understand decision making statements, loops, functions and  array  and other basic concepts.

In this post,  I have illustrated that how to make a factorial  function program  using for loop.   Hope you will understand   basic concepts  of loop and function.

References

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.