Python Finding Factorial Example

python-finding-factorial-ipcisco

In this Finding Factorial Python Example, we will do a basic Python practice. Here, we will try to print a factorial number result. In other words, we will do Python Factorial Example. So, what is factorial? Firstly, let’s start by explaining factorial in math.

 

Factorial is showed with an exclamation mark at the end of a number and it means the multiplication of the numbers from 1 to that number. For example, let’s talk about factorial 5. It is showed like below:

 

5!

 

And this means:

 

5 x 4 x 3 x 2 x 1 = 120

 

In this lesson, we will do this math process by the help of python programming. Normally, factorial is one of the most used exercises in programming classes and programming courses. So, here, we will show it with the help of python.

 

In our python factorial example, we will get an input from the user and as a result, we will print the factorial of that number. Below, you can find the coding example for this math function.

 

num = int(input("Enter a number:"))
factorial = 1
if num < 0:
   print("Factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

 

The output of this python code will ask a number from us. This will be input for this code and the program will give the factorial number of this code.

 

For example, if we write 5, the result will be like below:

 

Enter a number: 5

The factorial of 5 is 120

 

python-factorial-example-ipcisco

 

Now, let’s try Python Finding Factorial code with another number. This time, we will give 7 as an input.

 

 

num = int(input("Enter a number:"))
factorial = 1
if num < 0:
   print("Factorial does not exist for negative numbers")
elif num == 0:
   print("The factorial of 0 is 1")
else:
   for i in range(1,num + 1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

 

Enter a number: 7

The factorial of 7 is 5040

 

Finding Factorial is one of the common basic python programming examples. In all programming language practices, finding factorial is done. And these types of questions increase your if/else and elif statement capabilities. With more examples, you will get more familiar to these statements.

 

Back to: Python Programming Course > Basic Python Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand
Latest Blog Posts