Make a Calculator In Python
Posted Oct 16, 2023 07:11 PM
So, in this tutorial we will work on making a basic calculator in python language....Step-1 : Please Set Up Your Environment
So before you start, please make sure you have Python installed on your system. You can download Python from the official website
(https://www.python.org/downloads/) if it's not already installed.
Step-2 : Now you will create a Python File
Open your preferred text editor or Python IDE and create a new Python file. Then save it with a ".py" extension. Example, you can name it "calc.py."
Step-3 : Now please write the Calculator Code
Now, let's write the code for your calculator. Here We'll create a basic calculator that can perform the actions such as "addition", "subtraction", "multiplication", and "division:.
Example Code:
python
Code
# Simple Calculator in Python
# Function to perform addition
def add(x, y):
return x + y
# Function to perform subtraction
def subtract(x, y):
return x - y
# Function to perform multiplication
def multiply(x, y):
return x * y
# Function to perform division
def divide(x, y):
if y == 0:
return "Cannot divide by zero"
return x / y
# Main program
while True:
print("Options:")
print("Enter 'add' for addition")
print("Enter 'subtract' for subtraction")
print("Enter 'multiply' for multiplication")
print("Enter 'divide' for division")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input in ("add", "subtract", "multiply", "divide"):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if user_input == "add":
print("Result:", add(num1, num2))
elif user_input == "subtract":
print("Result:", subtract(num1, num2))
elif user_input == "multiply":
print("Result:", multiply(num1, num2))
elif user_input == "divide":
print("Result:", divide(num1, num2))
else:
print("Invalid input")Step-4 : Run the Calculator
Now please save the file and run it from your command prompt or terminal by navigating to the directory where your Python file is located and entering:
Copy code
python calc.py
After this, follow the on-screen instructions to perform calculations. You can enter "quit" to exit the calculator.
Note: This is a very basic calculator. If you want, you can enhance it by adding more functionality, error handling, and a graphical user interface (GUI) if you want to make it more user-friendly.
Any doubts please feel free to DM me on site.



