Simple Calculator in Python

Introduction

In this guide, you'll learn how to create a simple command-line calculator in Python.

Step 1: Define the Calculator Functions

Create a Python script with the following code:

def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: return "Error: Division by zero" return x / y # Main function to handle user input def calculator(): print("Select operation:") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter choice (1/2/3/4): ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(num1, "+", num2, "=", add(num1, num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1, num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1, num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1, num2)) else: print("Invalid input") # Run the calculator calculator()

Step 2: Run the Calculator

Save the Python script with a .py extension (e.g., calculator.py).

Open a terminal, navigate to the directory where the script is saved, and run:

python3 calculator.py

Step 3: Use the Calculator

Follow the prompts in the terminal to perform calculations with your simple Python calculator.

Conclusion

Congratulations! You've created a simple command-line calculator in Python. This calculator can perform basic arithmetic operations such as addition, subtraction, multiplication, and division. Experiment with the code and add more functionalities if desired!

Comments

Popular posts from this blog

Complete Guide to Clean and Optimize Ubuntu (Linux)

How to Install VirtualBox on Ubuntu (Linux)

How to Install FileZilla on Ubuntu (Linux)