Recursive Factorial Calculation in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120. In this challenge, you will write a Python function to calculate the factorial of a given number using recursion.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("`Raising Exceptions`") subgraph Lab Skills python/comments -.-> lab-13628{{"`Recursive Factorial Calculation in Python`"}} python/conditional_statements -.-> lab-13628{{"`Recursive Factorial Calculation in Python`"}} python/function_definition -.-> lab-13628{{"`Recursive Factorial Calculation in Python`"}} python/raising_exceptions -.-> lab-13628{{"`Recursive Factorial Calculation in Python`"}} end

Factorial

Write a function factorial(num) that takes a non-negative integer num as an argument and returns its factorial. The function should use recursion to calculate the factorial. If num is less than or equal to 1, return 1. Otherwise, return the product of num and the factorial of num - 1. The function should throw an exception if num is a negative or a floating-point number.

def factorial(num):
  if not ((num >= 0) and (num % 1 == 0)):
    raise Exception("Number can't be floating point or negative.")
  return 1 if num == 0 else num * factorial(num - 1)
factorial(6) ## 720

Summary

In this challenge, you learned how to calculate the factorial of a number using recursion. You also learned how to handle exceptions in Python.

Other Python Tutorials you may like