Python Calculator
In this quick post, we will see how we can create a very simple python calculator program. We will take input from the user about the operation he wants to perform and show the result on its basis. Let’s get started with our python calculator code right away.
Modular Code
To keep things modular, we will define functions to perform various operations. Here are the operations our calculator will support for numbers:
- Addition
- Subtraction
- Multiplication
- Division
- Raising a power to number
Addition
Let’s do our first operation of Addition here:
def addition(x, y):
return x + y;
We used a simple function so that our code remains modular.
Subtraction
Second operation involves subtracting two numbers:
def subtraction(x, y):
return x - y;
Multiplication
Third operation involves multiplying two numbers:
def multiplication(x, y):
return x * y;
Division
Fourth operation involves dividing two numbers:
def division(x, y):
return x / y;
Raising a power to number
Our final operation involves raising a number by a power. Note that to do this, we can use mathematical operator **
:
def raisePower(x, y):
return x ** y;
Taking user input
Time to present the user with available choices and taking an input from him:
print("Operation to perform:");
print("1. Addition");
print("2. Subtraction");
print("3. Multiplication");
print("4. Division");
print("5. Raising a power to number");
choice = input("Enter choice: ");
num1 = int(input("Enter first number: "));
num2 = int(input("Enter second number: "));
Deciding operation
Finally, we can decide which function to call when user has provided an input:
if choice == '1':
print(num1, "+" ,num2, "=", addition(num1, num2));
elif choice == '2':
print(num1, "-", num2, "=", subtraction(num1, num2));
elif choice == '3':
print(num1, "*", num2, "=", multiplication(num1, num2));
elif choice == '4':
print(num1, "/", num2, "=", division(num1, num2));
elif choice == '5':
print(num1, "**", num2, "=", raisePower(num1, num2));
else:
print("Please select a valid input.");
When we run this program, we will be able to perform mathematical operations:
Conclusion
In this quick post, we defined a very simple Python calculator and kept the code modular as well so that we can reuse the functions accordingly.