Python Calculator Simple Program

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 fornumbers:

  • Addition
  • Subtraction
  • Multiplication
  • Division
  • Raising a power to number


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.


Second operation involves subtracting two numbers:

def subtraction(x, y):
   return x - y;


Third operation involves multiplying two numbers:

def multiplication(x, y):
   return x * y;


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 aninput 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));

   print("Please select a valid input.");

When we run this program, we will be able to perform mathematical operations:

JournalDev责编内容来自:JournalDev (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Python Calculator Simple Program

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录