This is a basic Python program which helps school and college students to improve their knowledge in Python.
If you don’t know what is factorial, here is a small explanation,
Multiplying given integer with the sequence of descending positive integers is called factorial. For example,
5! is 5 x 4 x 3 x 2 x 1 = 120
So the value of 5! is 120
We can also find the values in the reverse way ie.,
5! is 1 x 2 x 3 x 4 x 5 = 120
In this program we are going to follow the above second method to find the value of the n! (n factorial)
Now, lets see the Python Factorial Program here:
print ("Enter Number to calculate Factorial: ")
#get the input
n = int(input())
fact = 1
print ("Factorial of", n, "is:")
#loop range from 1 to n
for i in range(1, n + 1):
fact = fact * i
print (fact)
This code works in both the Python 2 and Python 3 versions.
Let’s see the CGI version aka Python web version of this program:
#!/usr/bin/python
print "Content-type: text/html\n\n";
# Import modules for CGI handling
import cgi, cgitb
print '''
<html>
<head><title>Python CGI program to find n! (n factorial)</title></head>
<body>
<h3>Web Based Factorial Python script to find n! - <a href="http://www.tutorialsmade.com/">Tutorialsmade.com</a></h3>
<form action="" method="post">
<label>Enter Number to calculate Factorial:<label>
<input type="text" name="n" />
<input type="submit" value="Submit" />
</form><br /><br />
</body>
</html>
'''
# Create instance of FieldStorage
form = cgi.FieldStorage()
#get the input
n = form.getvalue('n')
if(n):
#type case string to int
n = int(n)
fact = 1
print "Factorial of", n, "is:", "<br>"
#loop range from 1 to n
for i in range(1, n + 1):
fact = fact * i
print fact,"<br>"
It’s same as the normal Python application program but the only difference is the extra Form added in this script.
Here is the demo of the above script:
