Python program to calculate the factorial of a number

In this program we will learn how to calculate the factorial of a number given by a user.

To understand this example, you should have the knowledge of following python topics –

  • Variables
  • Conditional statements
  • Loops(We have used the while loop here)
  • Incrementation

 

A fatorial is the multiplication of an integer and all the positive integers less than it. For example – The factorial of 4 is – 4 * 3 * 2 * 1 = 24.

Keep in mind that the factorial of a negative number is not defined and the factorial of 0 is always 1.

Program

num = int(input("Enter a number"))
fact = 1
i = 1
if num < 0:
    print("The number is negative")
elif num == 0:
    print("The factorial is 1")
else:
    while i <= num:
        fact = fact * i
        i += 1
    print("The factorial is ", fact)

Output

Enter a number5

The factorial is 120

Explanation

  • First of all we have declared a variable num and storing the value given by the user in it. The value is collected by the input function and the. When the program is executed, the user would see a message “Enter a number”. When the user enters a number, the number is converted to its equivalent integer form by the int function and gets stored in the variable num.
  • Then we have created two variables named fact and i and initialized them both with 1.
  • Next we have used the if….elif….else statements for different conditions, as the user could enter positive or negative numbers.
  • Inside the if statement we are checking if the number is less than 0. If the condition is true the program ends up by displaying a message “The number is negative”.
  • Inside the elif we are checking if the number is zero. If this condition is true, the message “The factorial is 0” would be displayed and the program would terminate.
  • If both the above conditions becomes false. That is, if the number is neither negative, nor zero, then the number must be positive. If this is so, the else part would be executed inside which we are calculating the factorial by using while loop.
  • The loop start from i = 1 and will run up to i = num (The number entered by the user). For instance, if the user enters 5, the loop will run from 1 to 5. The initial value of fact is 1. So the multiplication would be calculated in the following manner. In the first iteration fact * i that is 1 * 1 and this would  stored again in fact. In the second iteration, 1 * 2, in the third iteration 2 * 3 and so on until the loop terminates. The final value would be stored in the fact variable and the calculated value would be displayed.