The factorial of a positive integer n is the product of all positive integers less than or equal to n. The factorial of a number is represented by the symbol "!" . For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.
Here is a Python function that calculates the factorial of a given number using a for loop:
def factorial(n):
if n < 0:
return None
if n == 0:
return 1
result = 1
for i in range(1, n+1):
result *= i
return result
This function takes a single argument, n, and returns the factorial of n. It first checks if n is less than 0, if so it returns None. If n is equal to 0, it returns 1 (since the factorial of 0 is defined to be 1). It then initializes a variable named result to 1, then uses a for loop to iterate over the range of integers from 1 to n inclusive and multiply each number to result variable. Finally, the function returns the value of result, which is the factorial of n.
You can call this function and pass in any positive integer to calculate its factorial:
>>> factorial(5)
120
>>> factorial(3)
6
>>> factorial(10)
3628800
Alternatively python has math.factorial function which you can use without writing your own function.
import math
math.factorial(5)
Do note that factorial of number can be very large, even for relatively small numbers and python integers may not be large enough to store those values.
#1: Python program to find factorial of a given number without using recursion
- #Factorial without recursion
- n=int(input("Enter the number: "))
- fact=1
- if n<0:
- print("factorial doesn't exist for negative numbers")
- else:
- for i in range(1,n+1):
- fact=fact*i
- print("factorial of", n, "is", fact)
Output:
- Enter the number: 5
- factorial of 5 is 120
You Might like :
- Python try except else with example program
- Python finally block example with program
- Python try-except- else vs finally with example program
- Find factorial of a number without using recursion using python
- Python program to find factorial without recursion
- If statement in python example program
- Else statement in python with example program
- Types of operators in python
- python math operators
- python division operator
- Python modulo operator
- Python bitwise operators
- python comparison operators
- Logical operators in python
- Assignment operator in python
- Identity operator in python
- Python power operator
- Not equal operator in python
- python not operator
- python and operator
- python Ternary operator
- python string operations
- python string methods
- Spilt function in python
- Format function in python
- String reverse in python
- python tolower
- Remove spaces from string python
- Replace function in python
- Strip function in python
- Length of string python
- Concat python
- startswith python
- strftime python
- is numeric python
- is alpha python
- is digit python
- python substring
nice quick tip
ReplyDelete