Factorial Finder (Code) in Python

← Back to Projects

Factorial Finder in Python

About the project: create a Factorial Finder project in Python. This will be a self-contained script that allows you to calculate the factorial of a number.

This program will prompt you to enter a non-negative integer. It will then calculate and display the factorial of that number. The script will run in a continuous loop, so you can check as many numbers as you like without restarting.

How to use this Factorial Finder:

  • Run the Python script.
  • This script is ready to use. When you run it, you can enter a number, and it will immediately calculate and display its factorial.
  • You can keep entering numbers until you type q to quit.


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# factorial_finder.py

def find_factorial(num):
    """
    Calculates the factorial of a non-negative integer.

    The factorial of a number is the product of all integers
    from 1 to that number. The factorial of 0 is 1.

    Args:
        num (int): The number for which to find the factorial.

    Returns:
        int: The factorial of the number.
    """
    # Factorial is not defined for negative numbers.
    if num < 0:
        return None
    # The factorial of 0 is 1.
    if num == 0:
        return 1
    
    # Calculate the factorial using a loop.
    factorial = 1
    for i in range(1, num + 1):
        factorial *= i
    return factorial

def main():
    """
    Main function to run the Factorial Finder in a continuous loop.
    """
    print("--- Python Factorial Finder ---")
    print("Enter a non-negative integer to find its factorial (or 'q' to quit).")

    while True:
        try:
            user_input = input("\nEnter a number: ").strip()

            # Check if the user wants to quit
            if user_input.lower() == 'q':
                print("Exiting Factorial Finder. Goodbye!")
                break
            
            num = int(user_input)
            
            if num < 0:
                print("Factorial is not defined for negative numbers. Please enter a non-negative integer.")
                continue

            result = find_factorial(num)
            
            # Print the result
            print(f"The factorial of {num} is {result}.")

        except ValueError:
            print("Invalid input. Please enter a valid integer.")

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()