Given an integer 'n', output the factorial of the number.

Input 1: 3
Output 1: 6

Code

# Read the input
n = int(input())

# Factorial function
def factorial(x):
    
# Handle the edge case of 0. As you know, 0! = 1, you need to specify an explicit
# for this. 1 has also been included in the if statement since 1! also equals 1
    if(x==0 or x==1):
        return(1)

# If the above statement doesn't satisy, the function will go on so we don't need
# an else statement

# Initialise a variable 'ans' to 1. This will contain the final factorial of the
# given number
    ans = 1
    
# Run a loop from 2 to x    
    for i in range(2, x+1):

# With each iteration, just multiply 'ans' by i        
        ans = ans * i

# Return 'ans' from function        
    return(ans)
    
# Do not edit this portion (Printing the factorial)
print(factorial(n))

Comments