DEV Community

Cover image for Python 21: Factorial Calculator
Gregor Schafroth
Gregor Schafroth

Posted on

Python 21: Factorial Calculator

On my way to build an OpenAI ChatBot with Python I need to get better with coding, and for that I now started doing daily short exercises. Right now I’m getting them from ChatGPT. Here is a small Factorial Calculator I just made. (I know the logging is probably overkill but I just want to get in the habit of using that haha).

Do you know any other libraries I should learn to use or fun little exercises you think I should do?

# Exercise: Factorial Calculator

import logging

# Configure logging
logging.basicConfig(filename='factorial_calculator.log', level=logging.ERROR, format='%(asctime)s - %(levelname)s: %(message)s')

def calculate_factorial(number): # Calculate the factorial of a non-negative integer.
    if number < 0:
        return 'Not Defined (Factorials are not defiend for negative numbers)'
    elif number == 0:
        return 1
    result = 1
    while number > 1:
        result = result * number
        number = number - 1
    return result

def main():
    while True:
        user_input = input('input: ')
        try:
            number = int(user_input.strip())
            break
        except ValueError:
            logging.error('ValueError: Please enter a number')
    print(f'factorial: {calculate_factorial(number)}')

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)