Menu

gitpiper

factorial python Code Snippet in 2024

mathrecursionbeginner

Last Updated: 20 April 2024

Calculates the factorial of a number.

  • Use recursion.
  • If num is less than or equal to 1, return 1.
  • Otherwise, return the product of num and the factorial of num - 1.
  • Throws 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

python snippet similar to factorial For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️