Advanced Scientific Calculator Project with Python
Design and Development of an Advanced Scientific Calculator in Python: Integrating Arithmetic, Trigonometry, Logarithmic Functions, and Session-Based History for Enhanced User Experience
Project Overview
A calculator is one of the fundamental tools in computational programming, yet its scope extends far beyond basic arithmetic operations. In this project, we will implement an Advanced Scientific Calculator in Python. This calculator is designed to not only handle elementary operations such as addition, subtraction, multiplication, and division but also provide advanced mathematical functionalities. These include trigonometric calculations, logarithms, square roots, and hyperbolic functions.
Moreover, the program is interactive, menu-driven, and user-friendly. It maintains a history of all calculations performed during the session, enabling users to revisit previous results without the need to re-enter inputs. This project demonstrates how Python’s built-in libraries like math
and modular programming concepts can be utilized to create a robust application.
Key Features
- Basic Arithmetic: Addition, subtraction, multiplication, division.
- Advanced Functions: Power, factorial, square root, trigonometric and logarithmic operations.
- Conversion Tools: Radians-to-degrees, degrees-to-radians.
- Hyperbolic Functions: sinh, cosh, tanh.
- History Tracking: Maintains a list of all calculations performed.
- Interactive Menu: Guides users through all available operations step by step.
This project serves as an excellent exercise in Python programming, especially for beginners and intermediate developers looking to expand their knowledge of user interaction, error handling, and modular function design.
Flow of the Program
The calculator follows a systematic flow to ensure smooth user interaction and accurate calculations:
- Welcome Screen:
- The program starts by displaying a welcome message and a menu of operations.
- User Input:
- Users choose an operation by entering the corresponding menu number.
- Input Validation:
- The program ensures that users input valid numeric values, handling errors like invalid entries or division by zero.
- Perform Calculation:
- The program processes the input based on the selected operation and computes the result.
- Result Display and Logging:
- The result is displayed to the user and logged into a history list.
- Repeat or Exit:
- Users can perform additional calculations or exit the program.
This structured flow guarantees clarity and consistency, making the calculator intuitive and reliable.
Breaking Down the Code
1. Menu Display
The first step is creating a menu that lists all available operations. This is done in the display_menu()
function, which uses simple print
statements to organize the options neatly.
def display_menu():
print("\n--- Advanced Scientific Calculator ---")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Square Root")
# Additional options omitted for brevity
print("20. Exit")
This function is called in each iteration of the main program loop to remind the user of their choices.
2. Handling User Input
To ensure robustness, the get_input()
function manages numeric inputs. It uses a try-except
block to catch invalid entries and prompt the user until valid data is provided.
def get_input(prompt):
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a numerical value.")
return get_input(prompt)
By encapsulating input validation in a separate function, the program maintains clean, reusable code.
3. Performing Calculations
Each mathematical operation is implemented in its dedicated function. Below are some examples:
- Addition: Adds two numbers entered by the user:
def addition():
num1 = get_input("Enter the first number to add: ")
num2 = get_input("Enter the second number to add: ")
result = num1 + num2
log_calculation(result, f"{num1} + {num2}")
return result
- Square Root: Calculates the square root of a given number and handles negative input gracefully:
def square_root():
num = get_input("Enter the number to find the square root: ")
result = math.sqrt(num) if num >= 0 else "Error! Undefined for negative numbers."
log_calculation(result, f"sqrt({num})")
return result
- Logarithm: Computes the base-10 logarithm of a number and prevents errors for non-positive inputs:
def logarithm_base_10():
num = get_input("Enter the number to find the logarithm (base 10): ")
if num <= 0:
result = "Error! Logarithm of non-positive numbers is undefined."
else:
result = math.log10(num)
log_calculation(result, f"log10({num})")
return result
4. Maintaining History
The program records every calculation performed during a session in a list called history
. This feature is implemented in two parts:
- Logging Calculations: Each operation appends its result and expression to the
history
list:
def log_calculation(result, expression):
history.append(f"{expression} = {result}")
- Viewing History: Users can view their entire calculation history by selecting the corresponding menu option:
def view_history():
if not history:
print("No calculations performed yet.")
else:
print("\n--- Calculation History ---")
for entry in history:
print(entry)
5. Program Control
The main()
function is the backbone of the calculator. It continuously displays the menu, takes user input, and calls the appropriate function based on their choice. It also handles invalid inputs and exits the program when prompted.
def main():
while True:
display_menu()
choice = input("Select an operation (1-20): ")
try:
if choice == "1":
print("Result:", addition())
elif choice == "20":
print("Exiting... Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")
except Exception as e:
print(f"An error occurred: {e}")
Final Code
Here is the complete code for the Advanced Scientific Calculator
import math
# Store calculation history
history = []
def display_menu():
print("\n--- Advanced Scientific Calculator ---")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Square Root")
print("6. Power")
print("7. Sine")
print("8. Cosine")
print("9. Tangent")
print("10. Logarithm (base 10)")
print("11. Logarithm (custom base)")
print("12. Factorial")
print("13. Radians to Degrees")
print("14. Degrees to Radians")
print("15. Hyperbolic Sine (sinh)")
print("16. Hyperbolic Cosine (cosh)")
print("17. Hyperbolic Tangent (tanh)")
print("18. Percentage")
print("19. View Calculation History")
print("20. Exit")
def log_calculation(result, expression):
history.append(f"{expression} = {result}")
def get_input(prompt):
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a numerical value.")
return get_input(prompt)
def addition():
num1 = get_input("Enter the first number to add: ")
num2 = get_input("Enter the second number to add: ")
result = num1 + num2
log_calculation(result, f"{num1} + {num2}")
return result
def subtraction():
num1 = get_input("Enter the number you want to subtract from: ")
num2 = get_input("Enter the number to subtract: ")
result = num1 - num2
log_calculation(result, f"{num1} - {num2}")
return result
def multiplication():
num1 = get_input("Enter the first number to multiply: ")
num2 = get_input("Enter the second number to multiply: ")
result = num1 * num2
log_calculation(result, f"{num1} * {num2}")
return result
def division():
num1 = get_input("Enter the number to be divided: ")
num2 = get_input("Enter the divisor: ")
if num2 == 0:
result = "Error! Division by zero is undefined."
else:
result = num1 / num2
log_calculation(result, f"{num1} / {num2}")
return result
def square_root():
num = get_input("Enter the number to find the square root: ")
if num < 0:
result = "Error! Square root of a negative number is undefined."
else:
result = math.sqrt(num)
log_calculation(result, f"sqrt({num})")
return result
def power():
base = get_input("Enter the base number: ")
exponent = get_input("Enter the exponent: ")
result = math.pow(base, exponent)
log_calculation(result, f"{base} ^ {exponent}")
return result
def sine():
angle = get_input("Enter the angle in degrees: ")
result = math.sin(math.radians(angle))
log_calculation(result, f"sin({angle}°)")
return result
def cosine():
angle = get_input("Enter the angle in degrees: ")
result = math.cos(math.radians(angle))
log_calculation(result, f"cos({angle}°)")
return result
def tangent():
angle = get_input("Enter the angle in degrees: ")
result = math.tan(math.radians(angle))
log_calculation(result, f"tan({angle}°)")
return result
def logarithm_base_10():
num = get_input("Enter the number to find the logarithm (base 10): ")
if num <= 0:
result = "Error! Logarithm of non-positive numbers is undefined."
else:
result = math.log10(num)
log_calculation(result, f"log10({num})")
return result
def logarithm_custom_base():
num = get_input("Enter the number to find the logarithm: ")
base = get_input("Enter the base of the logarithm: ")
if num <= 0 or base <= 0:
result = "Error! Logarithm of non-positive numbers or base is undefined."
else:
result = math.log(num, base)
log_calculation(result, f"log({num}, base {base})")
return result
def factorial():
num = int(get_input("Enter the number to find the factorial: "))
if num < 0:
result = "Error! Factorial of a negative number is undefined."
else:
result = math.factorial(num)
log_calculation(result, f"{num}!")
return result
def radians_to_degrees():
radian = get_input("Enter the angle in radians: ")
result = math.degrees(radian)
log_calculation(result, f"radians({radian}) to degrees")
return result
def degrees_to_radians():
degree = get_input("Enter the angle in degrees: ")
result = math.radians(degree)
log_calculation(result, f"degrees({degree}) to radians")
return result
def hyperbolic_sine():
num = get_input("Enter the number to calculate sinh: ")
result = math.sinh(num)
log_calculation(result, f"sinh({num})")
return result
def hyperbolic_cosine():
num = get_input("Enter the number to calculate cosh: ")
result = math.cosh(num)
log_calculation(result, f"cosh({num})")
return result
def hyperbolic_tangent():
num = get_input("Enter the number to calculate tanh: ")
result = math.tanh(num)
log_calculation(result, f"tanh({num})")
return result
def percentage():
part = get_input("Enter the part value: ")
whole = get_input("Enter the whole value: ")
if whole == 0:
result = "Error! Division by zero is undefined."
else:
result = (part / whole) * 100
log_calculation(result, f"{part} is {result}% of {whole}")
return result
def view_history():
if not history:
print("No calculations performed yet.")
else:
print("\n--- Calculation History ---")
for entry in history:
print(entry)
def main():
while True:
display_menu()
choice = input("Select an operation (1-20): ")
try:
if choice == "1":
print("Result:", addition())
elif choice == "2":
print("Result:", subtraction())
elif choice == "3":
print("Result:", multiplication())
elif choice == "4":
print("Result:", division())
elif choice == "5":
print("Result:", square_root())
elif choice == "6":
print("Result:", power())
elif choice == "7":
print("Result:", sine())
elif choice == "8":
print("Result:", cosine())
elif choice == "9":
print("Result:", tangent())
elif choice == "10":
print("Result:", logarithm_base_10())
elif choice == "11":
print("Result:", logarithm_custom_base())
elif choice == "12":
print("Result:", factorial())
elif choice == "13":
print("Result:", radians_to_degrees())
elif choice == "14":
print("Result:", degrees_to_radians())
elif choice == "15":
print("Result:", hyperbolic_sine())
elif choice == "16":
print("Result:", hyperbolic_cosine())
elif choice == "17":
print("Result:", hyperbolic_tangent())
elif choice == "18":
print("Result:", percentage())
elif choice == "19":
view_history()
elif choice == "20":
print("Exiting... Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
sample output


--- Advanced Scientific Calculator ---
1. Addition
2. Subtraction
3. Multiplication
4. Division
...
12. Factorial
19. View Calculation History
20. Exit
Step 2: Select option 12 (Factorial) by entering 12
.Step 3: The program prompts:
Enter a number to calculate its factorial:
Enter 5
and press Enter.Step 4: The program computes the factorial using Python’s math.factorial
function:
5!=5×4×3×2×1=120
Step 5:The result is displayed:
The factorial of 5 is: 120
Step 6:The result is logged into the calculation history. To view the history:
Return to the main menu.
Select option 19 (View Calculation History) by entering 19.
The program displays the calculation history, including the current calculation:
--- Calculation History ---
5! = 120
Conclusion
This Advanced Scientific Calculator project exemplifies the power of Python in solving real-world problems. By combining modular programming, error handling, and user interaction, the calculator is a robust and versatile tool. Its extensibility allows for future enhancements, such as adding a graphical user interface (GUI), integrating with APIs, or supporting symbolic computation via libraries like SymPy
.
This project is an excellent stepping stone for anyone interested in Python programming, showcasing how even simple tools can be expanded into comprehensive applications through thoughtful design and implementation.