Introduction
Ever wanted to create your own calculator without relying on your phone? Now you can! Python makes it super easy to build a calculator that can handle basic arithmetic operations.
1. Basic Calculator using Python
Let's start with a simple calculator that can add, subtract, multiply, and divide numbers.
# Simple Python Calculator
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 "Error! Division by zero."
return x / y
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid input")
Boom! You now have a basic calculator in Python!
2. Making It More Fun
Let's add some personality to our calculator by making it respond in a fun way!
import random
def fun_response():
responses = ["Wow, you're a math genius!", "Nice calculation!", "Math is fun, right?"]
return random.choice(responses)
print("Welcome to the fun calculator!")
choice = input("Pick an operation (+, -, *, /): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '+':
print("Result:", num1 + num2, fun_response())
elif choice == '-':
print("Result:", num1 - num2, fun_response())
elif choice == '*':
print("Result:", num1 * num2, fun_response())
elif choice == '/':
if num2 == 0:
print("Oops! Can't divide by zero!")
else:
print("Result:", num1 / num2, fun_response())
else:
print("Invalid operation! Try again.")
Now your calculator gives motivational messages along with the result!
3. Expanding Features
Want to go even further? Here are some ideas:
- Add exponentiation (x^y).
- Include a square root function.
- Implement a GUI version using Tkinter.
import math
def square_root(x):
return math.sqrt(x)
Try adding this function to your calculator!
Conclusion
Building a calculator in Python is super easy and fun! Now, you can keep improving it by adding more features, making it smarter, or even turning it into a chatbot!
Happy coding!
0 Comments