def factorial(n):
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial(5))
print(factorial(3))
print(factorial(0))
#source code --> clcoding.com
Code Explanation:
Define the Function:
def factorial(n): → Defines the function, which takes n as input.
Handle Base Case (0 and 1):
if n == 0 or n == 1: return 1 → Since 0! = 1! = 1, return 1.
Initialize result to 1
result = 1 → This variable will store the factorial value.
Loop from 2 to n:
for i in range(2, n + 1): → Iterates through numbers from 2 to n.
result *= i → Multiplies result by i in each step.
Return the Final Result:
return result → Returns the computed factorial.
Example Output
120
6
1
0 Comments:
Post a Comment