Calculator Program In Python
If you are fresher in Python Programming and you want to create your first project in Python Programming then this blog “Calculator Program In Python” is for you. Create your first project “Calculator” using python programming language.
There are some questions that come to your mind, like what methods are used to create calculator in python programming. In this blog will explore how to create a calculator in Python, step by step.
Want to transform a career in Python Programming? Click here to join our Python Programming course today!
Simple Calculator Program In Python Using Function
def add(x, y):
return x + y def subtract(x, y):
return x - y def multiply(x, y):
return x * y def divide(x, y):
if y != 0:
return x / y
else:
return "Error: Cannot divide by zero" def main():
print("Simple Calculator Program in Python") num1 = float(input("Enter the first number: "))
operator = input("Enter the operator (+, -, *, /): ")
num2 = float(input("Enter the second number: ")) if operator == '+':
result = add(num1, num2)
elif operator == '-':
result = subtract(num1, num2)
elif operator == '*':
result = multiply(num1, num2)
elif operator == '/':
result = divide(num1, num2)
else:
result = "Error: Invalid operator" print(f"Result: {result}") if __name__ == "__main__":
main()
Output of the code-
Enter the first number: 15
Enter the operator (+, -, *, /):
Enter the second number: 3
Result: 45.0
Logic of code –
Used Arithmetic Operators In Python
- In this Code we used four operations – Addition, Subtraction, Multiplication
- Division operator used for checks for division by zero
User Input and Operator Handling
- “main function” takes user input for numbers and operators.
- Converts input to floats for decimal calculations.
- Uses if-elif-else to determine the selected operation.
Want to Learn Data Science With Python? Call us for career counseling +91 8600998107/+91 7028710777
Simple Calculator Program In Python Using A Class
class Calculator:
def add(self, x, y):
return x + y def subtract(self, x, y):
return x - y def multiply(self, x, y):
return x * y def divide(self, x, y):
if y != 0:
return x / y
else:
return "Error: Cannot divide by zero" def main():
calc = Calculator() print("Simple Calculator Program in Python") num1 = float(input("Enter the first number: "))
operator = input("Enter the operator (+, -, *, /): ")
num2 = float(input("Enter the second number: ")) if operator == '+':
result = calc.add(num1, num2)
elif operator == '-':
result = calc.subtract(num1, num2)
elif operator == '*':
result = calc.multiply(num1, num2)
elif operator == '/':
result = calc.divide(num1, num2)
else:
result = "Error: Invalid operator" print(f"Result: {result}") if __name__ == "__main__":
main()
Output of the code:
Enter the first number: 10
Enter the operator (+, -, *, /): *
Enter the second number: 5
Result: 50.0
Logic behind the Code:
- Defines a “Calculator” class with methods for addition, subtraction, multiplication, and division.
- Creates an instance of the Calculator class.
- Takes user input for two numbers and an operator.
- Performs the selected operation using the corresponding method of the Calculator object.
- Displays the result to the user.
Also Read: Leap Year Program In Python
Simple Calculator Program In Python Using Conditional Statements:
while True:
# Get the operator from the user
operator = input("Enter operator (+, -, *, /): ") # Get the first number from the user
num1 = float(input("Enter first number: ")) # Get the second number from the user
num2 = float(input("Enter second number: ")) # Check the operator and perform the corresponding operation
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
print("Division by zero is not allowed!")
else:
result = num1 / num2
else:
print("Invalid operator!") # Display the result
print("Result:", result) # Ask the user if they want to continue
choice = input("Do you want to continue? (yes/no): ")
if choice.lower() != "yes":
break
Output Of the code:
Enter operator (+, -, *, /): +
Enter first number: 5
Enter second number: 3
Result: 8.0
Do you want to continue? (yes/no): yes
Also Read: Prime Attribute In DBMS
How to build a calculator GUI in Python?
Step 1: Tkinter Setup
Import the “tkinter” library and create the main Tk instance.
Step 2: Calculator Class:
Create a “Calculator class” to encapsulate the calculator’s functionality.
Step 3: Entry Widget:
Use the Entry widget to display input and results.
Step 4: Buttons:
Create buttons for digits (0-9) and operations (+, -, *, /, =, etc.).
Step 5: Button Callbacks:
Set up callbacks for button clicks. The on_button_click method handles button presses.
Step 6: Evaluate Expression:
When the “=” button is clicked, use eval() to evaluate the expression and display the result.
Step 7: Main Loop:
Start the main loop with root.mainloop() to keep the GUI running.
Calculator Program:
import tkinter as tk class Calculator:
def __init__(self, root):
self.root = root
self.root.title("Simple Calculator") # Entry widget to display input and results
self.entry = tk.Entry(root, width=20, font=('Arial', 16), bd=5, insertwidth=4, justify='right')
self.entry.grid(row=0, column=0, columnspan=4) # Buttons for digits and operations
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
] # Initialize buttons and set their callbacks
row_val, col_val = 1, 0
for button in buttons:
tk.Button(root, text=button, width=5, height=2, command=lambda btn=button: self.on_button_click(btn)).grid(row=row_val, column=col_val)
col_val += 1
if col_val > 3:
col_val = 0
row_val += 1 def on_button_click(self, button):
current_entry = self.entry.get() if button == '=':
try:
result = eval(current_entry)
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, str(result))
except Exception as e:
self.entry.delete(0, tk.END)
self.entry.insert(tk.END, "Error") else:
self.entry.insert(tk.END, button) if __name__ == "__main__":
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
Also Read: How to check Armstrong Number In Python
Conclusion
I hope you get a better understanding of the Calculator Program In Python.
In this blog will explain some easy methods to create calculator in Python Programming –
- Create Calculator Using Function
- Create Calculator Using a Class
- Create Calculator using conditional statement
Whether you are a beginner looking to start or a working professional wanting to improve your skills, this blog will help you understand Python Programming simplicity and usefulness in software development better.
Want to transform a career in Python Programming? Click here to join our Python Programming course today! Call Us For more information.