Python Program to find the factorial of a number without recursion

PythonServer Side ProgrammingProgramming

When it is required to find the factorial of a number without using recursion, the ‘while’ loop can be used.

Example

Below is a demonstration for the same −

 Live Demo

my_num = int(input("Enter a number :"))
my_factorial = 1
while(my_num>0):
   my_factorial = my_factorial*my_num
   my_num=my_num-1
print("The factorial of the number is : ")
print(my_factorial)

Output

Enter a number :7
The factorial of the number is :
5040

Explanation

  • The input number is takne from the user.
  • A variable is assigned to 1.
  • It is checked to see for being 0.
  • If not, it is multiplied by the previous value in the variable.
  • It is assigned to the same variable.
  • This is done until the number reaches 0.
  • It is then displayed as output on the console.
raja
Published on 12-Mar-2021 12:32:54
Advertisements