Table of Contents
What is the factorial of a number?
The “factorial” of a number is that number multiplied by all the positive whole numbers less than it. It is written with an exclamation point, like “n!”.
can we have factorial for negative numbers?
No, we cannot factorial for negative numbers!
The factorial function is only defined for non-negative integers due to its origin in combinatorics.
It is the number of ways to arrange n objects. You can arrange any positive number of objects, so it is defined for positive numbers.
What is the factorial for the number
In a set of 0 items (an empty set) there is only one way to arrange them, therefore 0! = 1.
We will also treat non-numeric input values or negative numbers, returning None
Factorial function of a number in Python – the non-recursive version
def factorial(num): if type(num) != int: return None if num < 0: return None fact = 1 counter = 1 while counter <= num: fact = fact * counter counter += 1 return fact print(factorial(5)) print(factorial(-3)) print(factorial('abc'))
Factorial function of a number in Python – recursive version
def recFactorial(num): if type(num) != int: return None if num < 0: return None return num * factorial(num -1) print(recFactorial(5)) print(recFactorial(-3)) print(recFactorial('abc'))
Hello there!
I hope you find this post useful!I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.
If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!