Table of Contents
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.
To keep things modular, we will define functions to perform various operations. Here are the operations our calculator will support for numbers:
- Raising a power to number
Let’s do our first operation of Addition here:
Copydef addition(x, y): return x + y;
We used a simple function so that our code remains modular.
Second operation involves subtracting two numbers:
Copydef subtraction(x, y): return x - y;
Third operation involves multiplying two numbers:
Copydef multiplication(x, y): return x * y;
Fourth operation involves dividing two numbers:
Copydef 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
Copydef raisePower(x, y): return x ** y;
Taking user input
Time to present the user with available choices and taking an input from him:
Copyprint("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: "));
Finally, we can decide which function to call when user has provided an input:
Copyif 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:
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.