0% found this document useful (0 votes)
19 views6 pages

OOP Advanced Calculator in Python

The document describes the design and implementation of an advanced calculator using Object-Oriented Programming in Python. It outlines the functionalities such as various arithmetic operations, user input validation, and a menu-driven interface, all encapsulated within a class. The program emphasizes modularity and reusability, showcasing good software design practices.

Uploaded by

ANSHU S
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views6 pages

OOP Advanced Calculator in Python

The document describes the design and implementation of an advanced calculator using Object-Oriented Programming in Python. It outlines the functionalities such as various arithmetic operations, user input validation, and a menu-driven interface, all encapsulated within a class. The program emphasizes modularity and reusability, showcasing good software design practices.

Uploaded by

ANSHU S
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Advanced Calculator Using OOP in Python

Aim:
To design and implement an advanced calculator using Object-Oriented
Programming (OOP) in Python that performs a variety of arithmetic operations
such as addition, subtraction, multiplication, division, power, square root,
modulo, and floor division, while ensuring user input validation without using
try-except. The calculator should be menu-driven and structured using class and
object concepts for modularity and reusability.

Procedure:
 Define a class named AdvancedCalculator to encapsulate all calculator
functionality.
 Create a method display_menu() to show all available operations
(Addition, Subtraction, Multiplication, Division, Power, Square Root,
Modulo, Floor Division, Exit).
 Write an input validation method is_valid_number() that checks whether
the user input is a valid integer or float (including negative numbers)
without using exception handling.
 Create a method get_number(prompt) to take input from the user and
validate it using the previous method.
 Define a method perform_operation(choice) that:
 Takes the user's menu choice.
 Accepts input for one or two numbers as needed.
 Performs the selected operation.
 Handles edge cases like division by zero or square root of a
negative number.
 Create a loop in the run() method that:
 Continuously shows the menu.
 Accepts and processes the user's choice.
 Breaks the loop when the user selects "Exit".
 Create an object of the class and call the run() method to start the
calculator.
Source Code:
import math

class AdvancedCalculator:
def __init__(self):
[Link] = True

def display_menu(self):
print("\n===== Advanced Calculator =====")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. Power (x^y)")
print("6. Square Root (√x)")
print("7. Modulo (%)")
print("8. Floor Division (//)")
print("9. Exit")

def is_valid_number(self, s):


# Check if input is a valid integer or float (including negative)
return [Link]('.', '', 1).isdigit() or ([Link]('-') and s[1:].replace('.', '',
1).isdigit())

def get_number(self, prompt):


value = input(prompt)
if self.is_valid_number(value):
return float(value)
else:
print("Invalid input! Please enter a numeric value.")
return None

def perform_operation(self, choice):


if choice in ['1', '2', '3', '4', '5', '7', '8']:
num1 = self.get_number("Enter first number: ")
num2 = self.get_number("Enter second number: ")

if num1 is None or num2 is None:


return

if choice == '1':
print("Result:", num1 + num2)
elif choice == '2':
print("Result:", num1 - num2)
elif choice == '3':
print("Result:", num1 * num2)
elif choice == '4':
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Error: Cannot divide by zero.")
elif choice == '5':
print("Result:", num1 ** num2)
elif choice == '7':
print("Result:", num1 % num2)
elif choice == '8':
if num2 != 0:
print("Result:", num1 // num2)
else:
print("Error: Cannot perform floor division by zero.")

elif choice == '6':


num = self.get_number("Enter a number: ")
if num is not None:
if num >= 0:
print("Result:", [Link](num))
else:
print("Error: Cannot calculate square root of negative number.")

elif choice == '9':


print("Exiting Calculator. Thank you!")
[Link] = False
else:
print("Invalid choice. Please select a valid option.")

def run(self):
while [Link]:
self.display_menu()
user_choice = input("Enter your choice (1-9): ")
self.perform_operation(user_choice)

# Create object and run calculator


calc = AdvancedCalculator()
[Link]()

Sample Output:
===== Advanced Calculator =====
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Power (x^y)
6. Square Root (√x)
7. Modulo (%)
8. Floor Division (//)
9. Exit
Enter your choice (1-9): 1
Enter first number: 10
Enter second number: 25
Result: 35.0

Result:
The Advanced Calculator program using OOP in Python was successfully
developed. It:
 Accepts valid numeric inputs from users.
 Performs multiple arithmetic operations accurately.
 Demonstrates good software design practices through the use of class and
object, promoting modularity and reusability.

Common questions

Powered by AI

The is_valid_number() method currently validates numeric inputs by assessing whether the input string can be transformed into a floating-point or integer representation, using string checks for numeric content and negative signs. While effective for basic validation, this method may fall short with complex strings containing characters like spaces, commas, or atypical decimal formats. Enhancements could involve implementing regex patterns to validate diverse numeric formats, thereby expanding its robustness. Additional features like locale-specific formatting might also be considered for broader applicability and user-friendliness across different regions or input styles .

Encapsulation in the AdvancedCalculator program is achieved by defining a class that encapsulates all functionalities of the calculator through its methods. Methods like display_menu(), is_valid_number(), get_number(), perform_operation(), and run() are encapsulated within the class. This structure keeps related data and behaviors together, allowing the user to interface with the calculator through straightforward and isolated actions without worrying about the internal workings. Encapsulation enhances the calculator's functionality by improving code organization, modularity, and maintainability, allowing for easy updates and extensions without affecting other parts of the program .

The calculator addresses division by zero by checking if the second number is zero before performing division or floor division. If it is zero, it outputs an error message stating that division or floor division by zero is not possible, preventing the undefined mathematical operation. Similarly, for computing the square root, the program checks if the input number is non-negative. If the number is negative, it prints an error message indicating that the square root of a negative number cannot be calculated. This preventive approach to error handling ensures that invalid operations do not occur and that the program remains stable and user-friendly .

math.sqrt() in the Advanced Calculator is used to compute the square root of a number when performing the respective operation. This ensures accurate computation consistent with the mathematical definition of square roots. A potential improvement could include providing an explanation or justification to the user when negative numbers are input, enhancing user understanding and interaction. Additionally, using exception handling to catch inappropriate inputs directly within this computation could offer another layer of robustness, despite the current design choice to avoid try-except blocks .

User input in the run() method is crucial as it directly influences the program flow of the Advanced Calculator. By continuously presenting the menu and awaiting user choice, the program can dynamically respond to user requests for operations. The run() method orchestrates this interaction, using user_choice to decide the next action, enabling a responsive and iterative user experience. This design ties the program's activity to user engagement, demonstrating event-driven programming principles that allow efficient, user-centric operation and control .

Structuring the Advanced Calculator as a menu-driven program provides an intuitive user experience, making it easier to understand and use. The use of a loop in the run() method continuously presents the menu and processes user input until the exit option is chosen, enhancing user engagement and allowing multiple operations without restarting the program. However, potential limitations include becoming cumbersome if the menu options grew significantly, requiring more sophisticated navigation like submenus. Additionally, it assumes sequential user interaction, which might not be suitable for more complex or varied use cases where concurrent operations might be beneficial .

The AdvancedCalculator class design supports extensibility through its encapsulated structure and clear separation of operations. Adding new operations would involve minimal changes—such as modifying display_menu() to include new menu options, updating perform_operation() to handle new operations logic, and ensuring relevant input is captured and validated. The class's modularity, achieved by separating input handling, operation logic, and user interaction, facilitates straightforward extensions without needing major architectural changes, allowing developers to maintain and upgrade the calculator efficiently .

The core components of the AdvancedCalculator class include methods such as display_menu(), is_valid_number(), get_number(prompt), perform_operation(choice), and run(). display_menu() ensures user interaction by listing out all possible operations, contributing to a predictable and user-friendly interface. is_valid_number() ensures input validation by checking if the input is a valid number, promoting robust input handling without try-except. get_number(prompt) utilizes input validation to safely obtain user inputs. perform_operation(choice) handles the logic of executing the appropriate arithmetic operations and managing edge cases like division by zero, ensuring modularity by separating concerns. These components collectively enhance reusability by clearly defining individual functionalities and interactions between them, embodying the principles of encapsulation and separation of concerns .

Avoiding exception handling can lead to challenges when unexpected input formats occur, as the is_valid_number() logic could fail with extremely unusual inputs (e.g., inputs with multiple invalid characters). Such issues might lead to improper feedback or system crashes. Addressing these challenges under the current design necessitates ensuring rigorous input validation, possibly expanding the is_valid_number() function to cover additional edge cases, and could involve pre-parsing the input to remove whitespace or recognize other acceptable number formats before validation. Improving user guidance on expected input formats can also help mitigate such risks .

The AdvancedCalculator program uses the is_valid_number() method to handle input validation. This method checks if the input string represents a valid integer or floating-point number by removing any one occurrence of a decimal point and then checking if the resulting string is numeric, allowing for negative values by also checking if the string starts with a '-' before the numeric check. This approach prevents program crashes due to invalid inputs while maintaining control flow without relying on exception handling, thus simplifying debugging and improving performance because exceptions are computationally expensive .

You might also like