Categories We Write About

Build a command-line calculator

Creating a command-line calculator in Python is straightforward and can be done with a simple script. Below is a basic example that supports addition, subtraction, multiplication, and division. It continuously prompts the user for input until they type “exit”.

python
def calculator(): print("Simple Command-Line Calculator") print("Type 'exit' to quit") while True: expression = input("Enter calculation (e.g. 2 + 3): ") if expression.lower() == "exit": print("Goodbye!") break try: # Evaluate the expression safely result = eval(expression, {"__builtins__": None}, {}) print("Result:", result) except Exception as e: print("Error:", e) if __name__ == "__main__": calculator()

How it works:

  • The user inputs a math expression like 5 + 7 or 12 / 4.

  • The script uses Python’s eval() with restricted built-ins for safety.

  • Errors (like syntax or division by zero) are caught and displayed.

  • Type exit to quit the program.

Would you like me to create a more advanced version with support for functions or a GUI?

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About