allthefactorials.py

Created by matt-numworks

Created on November 25, 2025

1.1 KB

Calculate single, double, triple factorials


# Type your text herefrom math import gamma, sqrt
from math import *

def factorial(x):
    return gamma(x + 1)

def double_factorial(n):
    result = 1
    while n > 1:
        result *= n
        n -= 2
    return result

def triple_factorial(n):
    result = 1
    while n > 1:
        result *= n
        n -= 3
    return result

while True:
    expr = input("Enter n!, n!!, or n!!! \n(or 'quit' to exit): ")

    if expr.lower() in ("quit", "exit"):
        print("Goodbye!")
        break
      
    bangs = 0
    while expr.endswith("!"):
        bangs += 1
        expr = expr[:-1]

    if bangs not in (1, 2, 3):
        print("Use 1, 2, or 3 factorials.")
        continue

    try:
        x = eval(expr)
    except:
        print("Invalid number or expression.")
        continue

    if bangs == 1:
        value = factorial(x)
    else:
        if x < 0 or int(x) != x:
            print("Double/triple factorial needs a non-negative integer.")
            continue
        n = int(x)
        value = double_factorial(n) if bangs == 2 else triple_factorial(n)

    print("Result:", value)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.