Created by Kevin TigheLinked to 64.4m issues across 157 teams
Here's how to write a function in Python that calculates the factorial of a given number.
First, start by importing the sys module:
import sys
Next, define the function Factorial, which will take one argument, n, and return the factorial of that number:
def Factorial(n): # return factorial
Inside the function, create a variable called result and set it to 1. This will be used to store the result of the calculation:
result = 1
Now, create a for
loop that will iterate from 1 to n. For each iteration, multiply the result by the current value of i and store the result in the result variable:
for i in range (1,n): result = result * i
Finally, print the result and return it:
print "factorial is ",result return result
Now, you can call the function with any number to get the factorial of that number:
print Factorial(10)
Contributor
Teams
157