Introduction
A scientific calculator goes beyond basic arithmetic operations to include functions like trigonometry, logarithms, and more. Building a scientific calculator in Python is a fantastic project that helps you learn about user interfaces, mathematical functions, and error handling. In this post, we’ll design a console-based scientific calculator, outlining its features and implementation step by step.
Features of a Scientific Calculator
Before we start coding, let’s outline the features we want in our scientific calculator:
- Basic Operations: Addition, subtraction, multiplication, and division.
- Scientific Functions: Trigonometric functions (sine, cosine, tangent), logarithmic functions, and exponentiation.
- Input Validation: Handle invalid inputs gracefully.
- Exit Option: Allow users to exit the program easily.
Step 1: Setting Up Your Environment
- Install Python: Ensure you have Python installed. Download it from the official Python website.
- Choose an IDE: Use any text editor or IDE (like VS Code, PyCharm, or IDLE).
Step 2: Write the Code
Let’s start coding our scientific calculator.
- Create a New Python File (e.g., scientific_calculator.py).
- Import Required Libraries: We’ll need the math library for mathematical functions.
import math
- Define Functions for Each Operation:
We will create functions for both basic and scientific operations.
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
def sine(x):
return math.sin(math.radians(x))
def cosine(x):
return math.cos(math.radians(x))
def tangent(x):
return math.tan(math.radians(x))
def logarithm(x, base):
return math.log(x, base)
def exponentiation(x, y):
return math.pow(x, y)
-
Create a Function to Display the Menu:
This function will show the user available operations.
def display_menu():
print("\nSelect operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Sine")
print("6. Cosine")
print("7. Tangent")
print("8. Logarithm")
print("9. Exponentiation")
print("10. Exit")
-
Get User Input and Perform Operations:
We’ll write the main logic to get user input and call the appropriate function based on their choice.
def main():
while True:
display_menu()
choice = input("Enter choice (1-10): ")
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
elif choice in ['5', '6', '7']:
angle = float(input("Enter angle in degrees: "))
if choice == '5':
print(f"sine({angle}) = {sine(angle)}")
elif choice == '6':
print(f"cosine({angle}) = {cosine(angle)}")
elif choice == '7':
print(f"tangent({angle}) = {tangent(angle)}")
elif choice == '8':
num = float(input("Enter number: "))
base = float(input("Enter base: "))
print(f"logarithm({num}, {base}) = {logarithm(num, base)}")
elif choice == '9':
num1 = float(input("Enter base: "))
num2 = float(input("Enter exponent: "))
print(f"{num1} ^ {num2} = {exponentiation(num1, num2)}")
elif choice == '10':
print("Exiting the calculator. Goodbye!")
break
else:
print("Invalid input! Please enter a number between 1 and 10.")
-
Run the Main Function:
Finally, add the line to execute the main() function when the script runs.
if __name__ == "__main__":
main()
Full Code
Here’s the complete code for your scientific calculator:
import math
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
def sine(x):
return math.sin(math.radians(x))
def cosine(x):
return math.cos(math.radians(x))
def tangent(x):
return math.tan(math.radians(x))
def logarithm(x, base):
return math.log(x, base)
def exponentiation(x, y):
return math.pow(x, y)
def display_menu():
print("\nSelect operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Sine")
print("6. Cosine")
print("7. Tangent")
print("8. Logarithm")
print("9. Exponentiation")
print("10. Exit")
def main():
while True:
display_menu()
choice = input("Enter choice (1-10): ")
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
elif choice in ['5', '6', '7']:
angle = float(input("Enter angle in degrees: "))
if choice == '5':
print(f"sine({angle}) = {sine(angle)}")
elif choice == '6':
print(f"cosine({angle}) = {cosine(angle)}")
elif choice == '7':
print(f"tangent({angle}) = {tangent(angle)}")
elif choice == '8':
num = float(input("Enter number: "))
base = float(input("Enter base: "))
print(f"logarithm({num}, {base}) = {logarithm(num, base)}")
elif choice == '9':
num1 = float(input("Enter base: "))
num2 = float(input("Enter exponent: "))
print(f"{num1} ^ {num2} = {exponentiation(num1, num2)}")
elif choice == '10':
print("Exiting the calculator. Goodbye!")
break
else:
print("Invalid input! Please enter a number between 1 and 10.")
if __name__ == "__main__":
main()
Step 3: Test Your Calculator
- Run the Script: Open your terminal or command prompt, navigate to the directory where your scientific_calculator.py file is located, and run:
python scientific_calculator.py
- Interact with the Calculator: Follow the prompts to perform calculations and test all functions to ensure they work correctly.
Step 4: Enhancements (Optional)
Once you’ve successfully built the scientific calculator, consider adding enhancements:
- Advanced Functions: Include features like factorial, square roots, or complex numbers.
- Graphical User Interface (GUI): Use libraries like Tkinter to create a GUI for a more user-friendly experience.
- History Functionality: Keep track of previous calculations.
Conclusion
Congratulations on building a scientific calculator in Python! This project has introduced you to various programming concepts while allowing you to apply your knowledge in a practical way. As you continue to learn, consider expanding your calculator with additional features or even exploring other projects.