# Python Factorials

Factorials are a fundamental element in many functional programming languages, including Python. Factorials are useful in teaching functional programming because they can be solved using multiple methods that illustrate several concepts.

In this blog we will cover how to solve factorials using four different methods. These include recursion, loops, an external library, and a technique called memoization. We will walk through the pros and cons of each method and discuss the tradeoffs of each solution.

Recursion

Factorials, denoted by the exclamation point, are a product of all positive integers less than or equal to n. For example:

4! = 4 * 3 * 2 * 1 = 24

The factorial function is typically used in combinatorics, probability theory and other related mathematical areas.

In this post, we will cover how to create a recursive program to compute factorials in Python. While at Dataquest we advocate getting used to consulting the Python documentation, sometimes it’s nice to have a handy PDF reference, so we’ve put together this Python regular expressions (regex) cheat sheet to help you out! This regex cheat sheet is based on Python 3’s documentation on regular expressions.

The cheat sheet not only includes the Python regex basics but also provides examples for matching specific number patterns and currency symbols. You can download the latest version of our Python regular expressions cheat sheet here:

Python Regex Cheat Sheet: A Quick Guide to Regular Expressions in Python – Dataquest

In this article, we’ll walk through writing a program to calculate the factorial of a number using recursion in Python. If you’re new to recursion and functional programming, you might find this post a bit challenging.

Eventually, we will come up with the following solution:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

print(factorial(5))

The factorial of a number is the product of an integer and all the integers below it. For example, the factorial of five ( 5! ) is equal to 1 x 2 x 3 x 4 x 5 = 120 .

In this tutorial, we will write a simple Python program to calculate the factorial of a number by using a for loop.

For Loop

The following code uses a for loop to find the factorial of a number:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

print (factorial(4))

import math

def factorial(n):

if n == 1:

return 1

else:

return n*factorial(n-1)

print (factorial(5))