Creating a simple calculator using Python

Creating a simple calculator using Python is an excellent way to explore programming logic and fundamental arithmetic operations. Python's versatility makes it straightforward to build a command-line calculator, offering an educational journey into programming. Let's walk through the steps to create your calculator using Python without a graphical user interface (GUI).


Understanding the Approach

Python's basic arithmetic operations (+, -, *, /) form the foundation for our calculator. We'll utilize functions to handle each operation and gather user input to perform calculations. This calculator will operate within the terminal, providing an accessible interface for basic arithmetic.


Let's Dive into the Code!

Firstly, create a Python file—let's name it `calculator.py`— to contain the code for the calculator. This file will comprise functions for addition, subtraction, multiplication, division, and a primary function to manage user input.

Python
#Code Starts

# first num

var1 = int(input("Enter Your First Number: "))

# second num

var2 = int(input("Enter Your Second Number: "))

# Operator

var3_operator = input("Enter Operator (+,-,*,/) : ")

# main 

if var3_operator == "+":

    print(var1 + var2)

elif var3_operator == "-":

    print(var1 - var2)

elif var3_operator == "*":

    print(var1 * var2)

elif var3_operator == "/":

    print(var1 / var2)

else: print("Wrong Selection")

input()


Running the Calculator

1. Save the code into a file named `calculator.py`.

2. Open a terminal or command prompt.

3. Navigate to the directory containing the `calculator.py` file.

4. Run the calculator by typing `python calculator.py`.

5. Follow the instructions in the terminal to perform calculations.


Conclusion

Congratulations! You've successfully created a simple yet functional calculator using Python. To deepen your learning, consider adding more operations, error handling, or additional functionalities.


Building a calculator serves as an excellent starting point to explore Python's capabilities in managing user input, functions, and basic arithmetic operations. Enjoy experimenting and expanding this project further!

Previous Post Next Post