0% found this document useful (0 votes)
31 views

Contents Python Merged

Uploaded by

vikirna.03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Contents Python Merged

Uploaded by

vikirna.03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

CALCULATOR

A PROJECT REPORT

Submitted by

AKANKSHA SEMWAL [ RA2311003030345]


VIKIRNA MAJUMDAR [RA2311003030350]
ANKIT RAJ [ RA2311003030352]
DARSHANA KRISHNA [RA2311003030356]

Under the guidance of

Ms. Swati Sheoran


(Assistant Professor, Department of Computer Science & Engineering)

SRM INSTITUTE OF SCIENCE & TECHNOLOGY, NCR CAMPUS


SRM INSTITUTE OF SCIENCE &
TECHNOLOGY
(Under Section 3 of UGC Act, 1956)

BONAFIDE CERTIFICATE

Certified to be the bonafide record of work done by AKANKSHA SEMWAL


[RA2311003030345] of 3rd semester 2nd year B.TECH degree course in SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY, NCR Campus of Department of
Computer Science & Engineering in Advanced Programming Practice Lab, during the
academic year 2024-2025.

SIGNATURE SIGNATURE

Ms. Swati Sheoran Dr. Avneesh Vashistha


Assistant Professor Head of the Department
Computer Science & Engineering Computer Science & Engineering
SRM INSTITUTE OF SCIENCE &
TECHNOLOGY
(Under Section 3 of UGC Act, 1956)

BONAFIDE CERTIFICATE

Certified to be the bonafide record of work done by VIKIRNA MAJUMDAR


[RA2311003030350] of 3rd semester 2nd year B.TECH degree course in SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY, NCR Campus of Department of
Computer Science & Engineering in Advanced Programming Practice Lab, during the
academic year 2024-2025.

SIGNATURE SIGNATURE

Ms. Swati Sheoran Dr. Avneesh Vashistha


Assistant Professor Head of the Department
Computer Science & Engineering Computer Science & Engineering
SRM INSTITUTE OF SCIENCE &
TECHNOLOGY
(Under Section 3 of UGC Act, 1956)

BONAFIDE CERTIFICATE

Certified to be the bonafide record of work done by ANKIT RAJ [RA2311003030352]


of 3rd semester 2nd year B.TECH degree course in SRM INSTITUTE OF SCIENCE
AND TECHNOLOGY, NCR Campus of Department of Computer Science &
Engineering in Advanced Programming Practice Lab, during the academic year 2024-
2025.

SIGNATURE SIGNATURE

Ms. Swati Sheoran Dr. Avneesh Vashistha


Assistant Professor Head of the Department
Computer Science & Engineering Computer Science & Engineering
SRM INSTITUTE OF SCIENCE &
TECHNOLOGY
(Under Section 3 of UGC Act, 1956)

BONAFIDE CERTIFICATE

Certified to be the bonafide record of work done by DARSHANA KRISHNA


[RA2311003030356] of 3rd semester 2nd year B.TECH degree course in SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY, NCR Campus of Department of
Computer Science & Engineering in Advanced Programming Practice Lab, during the
academic year 2024-2025.

SIGNATURE SIGNATURE

Ms. Swati Sheoran Dr. Avneesh Vashistha


Assistant Professor Head of the Department
Computer Science & Engineering Computer Science & Engineering
Table of Contents

S.N. Topics Page No

1 Introduction of the Project 1

2 Project Review 3

3 Features 4

4 Calculator Implementation 6
● 4.1. Basic Operations
● 4.2. Advanced Operations

5 Use Interface 8

6 Running the Calculator 11

7 Conclusions 16
CALCULATOR
1. INTRODUCTION
In today's fast-paced digital world, calculators are essential tools that help
simplify complex mathematical calculations. From basic arithmetic operations
to advanced mathematical functions, calculators are indispensable for students,
professionals, and individuals alike. With the advent of programming languages
like Python, creating custom calculators tailored to specific needs has become
easier and more accessible.

This project aims to develop a Python-based calculator that can handle


both basic and advanced arithmetic operations. The project offers a
hands-on opportunity to learn and understand the fundamental principles of
programming, including how to manage user input, apply mathematical
operations, handle errors gracefully, and design a simple yet effective
command-line interface.

The calculator in this project will feature operations such as addition,


subtraction, multiplication, and division, as well as more advanced features
like modulus, exponentiation, and square root calculations. Python’s simplicity
and flexibility make it an ideal language to implement this project, as it allows
for quick development and easy expansion of features.

Furthermore, the project serves as an introduction to stack-based computation,


where arithmetic operations follow a specific sequence dictated by operator
precedence and associativity. This allows for a deeper understanding of how
calculators handle complex expressions and operations in a sequential and
logical manner.

The project is designed with scalability in mind, meaning users can extend
its functionality to include more advanced mathematical functions, such as
trigonometry or logarithmic operations, or even build a graphical user
interface (GUI) for enhanced interactivity.

In addition to implementing the calculator itself, this project will explore


important programming concepts such as modular design, where different
operations are broken down into individual functions, allowing for cleaner,

Page | 1
more organized code. The project will also incorporate error handling
techniques to manage common issues like division by zero or invalid input.
By the end of this project, you will have developed a fully functional calculator,
gained valuable experience in Python programming, and understood how to
design a user-friendly command-line tool that effectively manages mathematical
operations. This project is not only a practical exercise but also a stepping stone
for more advanced programming challenges.

In summary, this Python calculator project:


• Introduces the development of basic and advanced mathematical functions.
• Demonstrates the power of modular and organized code.
• Explains error handling and input validation.
• Provides a foundation for expanding into more complex
applications, including graphical user interfaces.

This project is ideal for beginners looking to improve their programming skills
and intermediate developers wanting to deepen their understanding of algorithm
design and Python programming fundamentals.

Page | 2
2. PROJECT OVERVIEW
The Python-based calculator project is designed to create a simple yet flexible
tool for performing both basic and advanced mathematical operations. It aims to
provide users with a command-line interface where they can execute operations
like addition, subtraction, multiplication, division, and more advanced functions
like modulus, exponentiation, and square root.

Problem Statement:
While most calculators are either overly simplistic or too complex for casual
users, this project addresses the need for a customizable, user-friendly calculator
that balances simplicity with functionality. It offers a tool that can handle a wide
range of calculations while allowing for easy extension and modification.

Objectives:
The project aims to:
1. Develop a fully functional command-line calculator that performs both
basic and advanced operations.
2. Ensure the calculator is user-friendly, with proper input validation and
error handling.
3. Design the code with scalability in mind, allowing for future additions
like more advanced functions or a graphical user interface (GUI).

Scope and Challenges:


The calculator will focus on providing basic arithmetic operations, advanced
calculations, and error-handling mechanisms to prevent issues like division by
zero or invalid inputs. Key challenges include ensuring smooth user interaction,
accurate calculations, and clean, maintainable code for future extensions.

Page | 3
3. FEATURES
The Python calculator project is designed to offer a comprehensive set of
features that enhance its usability and functionality. The features are divided
into two main categories: basic arithmetic operations and advanced
mathematical operations, along with robust error handling and an intuitive user
interface. These features make the calculator versatile, easy to use, and suitable
for both casual users and those requiring more complex calculations.

Basic Arithmetic Operations:

The calculator performs essential arithmetic operations that form the foundation
of its functionality. These include:
- Addition (+): Adds two numbers and returns the result. This
operation is fundamental for simple calculations.
- Subtraction (−): Subtracts one number from another, allowing
users to compute differences quickly and accurately.
- Multiplication (×): Multiplies two numbers, supporting everyday
tasks like finding totals, areas, or product quantities.
- Division (÷): Divides one number by another. The calculator ensures
division by zero is handled gracefully with proper error messages.

These operations cover the basic needs of any calculator user, making it ideal
for solving everyday mathematical problems, from balancing budgets to
calculating measurements.

Advanced Mathematical Operations:

In addition to basic arithmetic, the calculator supports several advanced


mathematical operations, making it useful for more complex calculations:
- Modulus (%): Computes the remainder when one number is divided
by another. This is especially useful in programming, mathematical proofs,
and modular arithmetic.
- Exponentiation (^): Raises one number to the power of another,
allowing users to perform exponential calculations like squares, cubes, and
higher powers.
- Square Root (√): Calculates the square root of a given number. The
calculator handles negative inputs by providing an appropriate error message,
preventing undefined results.

Page | 4
- Floor Division (//): Performs division and returns the largest integer
smaller than or equal to the result, useful in cases where you need
rounded-down division.

These advanced features cater to users who require more than just basic
arithmetic, such as students working on algebra or professionals handling
scientific computations.

Error Handling Mechanism:

A significant focus of this project is ensuring that errors are handled smoothly,
preventing the program from crashing and giving users clear feedback on
mistakes:
- Division by Zero: When a user attempts to divide by zero, the
calculator detects this error and returns a user-friendly message, rather than
allowing the program to crash.
- Invalid Input: The calculator ensures that only valid numerical inputs
are accepted. If a user enters non-numeric data, such as letters or special
characters, an error message is displayed prompting the user to try again.
- Negative Square Root: The calculator avoids undefined results by
detecting attempts to calculate the square root of a negative number and alerts
the user to the error.
- Overflow and Precision: The calculator is built to handle large
numbers and precision issues, ensuring that results for large exponentiations
or very small numbers are calculated accurately, and error handling is in place
for extreme cases.

Page | 5
4. CALCULATOR IMPLEMENTATION
The implementation of the Python-based calculator focuses on modularity,
clarity, and ease of use. This section explains the key components of the
calculator’s implementation, including how the operations are structured, the
user interface, input validation, error handling, and code scalability.

Modular Design:

The core of the calculator’s implementation is its modular design, which


ensures that each operation is handled by a separate function. This approach not
only simplifies the code but also makes it easy to debug and extend. Here’s how
the modular structure is organized:
- Basic Operations: Functions for addition, subtraction, multiplication,
and division are created, each taking two input values and returning the result.
These functions are concise and reusable across the application.
- Advanced Operations: Additional functions for more complex
calculations, such as modulus, exponentiation, and square root, are
implemented separately. Each function is designed to handle specific edge
cases, such as negative inputs for square roots.

This modularity ensures that the code remains clean and easy to manage. New
operations can be added without changing the entire codebase, allowing for
flexibility in future updates.

4.1. BASIC OPERATIONS

Page | 6
def add(a, b):
return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b): if


b != 0:
return a / b
else:
return "Error: Division by zero"
4.2. BASIC OPERATIONS

Page | 7
import math

def modulus(a, b):


return a % b

def exponent(a, b):


return a ** b

def square_root(a):
if a >= 0:
return math.sqrt(a)
else:
return "Error: Cannot calculate square root of a negative number"

5. USER INTERFACE
The calculator project is designed to provide a simple yet efficient Command-
Line Interface (CLI) that allows users to perform calculations easily. The user
interface prioritizes clarity, responsiveness, and ease of navigation, ensuring a
seamless experience for both novice and experienced users. Below are the
key elements that define the user interface.

1. Menu System
The main interaction with the calculator begins with a clear and
easy-to- navigate menu. Upon launching the program, users are
presented with a numbered list of available operations, such as:
- 1. Addition
- 2. Subtraction
- 3. Multiplication
- 4. Division
- 5. Modulus
- 6. Exponentiation
- 7. Square Root

Users simply need to type the corresponding number for their desired
operation. This menu system is intuitive, allowing users to navigate quickly
through the available options without having to type complex commands.

2. User Prompts for Inputs


After selecting an operation, the calculator prompts the user to input
the required values:

Page | 8
- Basic Operations: For addition, subtraction, multiplication, and
division, the user is asked to enter two numbers (e.g., "Enter first number:").
- Advanced Operations: For functions like square root, the calculator
requests only one number. In cases like exponentiation or modulus, it prompts
for both the base and exponent or dividend and divisor, respectively.

The prompts are clear and guide the user step-by-step, ensuring they know
exactly what is required at each stage of the calculation.

3. Continuous Mode
After completing a calculation, the interface offers users the choice to either:
- Perform another calculation, or
- Exit the program.

Page | 9
This continuous mode allows users to carry out multiple operations in one
session without restarting the program. A typical workflow looks like
this:
1. Select operation →
2. Enter numbers →
3. Display result →
4. Ask if the user wants to perform another calculation or exit.

This loop creates a seamless and uninterrupted experience, making


the calculator more practical for extended use.

4. Clear Output Display


Once a calculation is completed, the result is displayed in a straightforward
format, often along with the operation performed for clarity. For example:
- Addition: "The result of 5 + 3 is 8."
- Division: "The result of 10 ÷ 2 is 5."

This ensures users can easily understand the results of their calculations without
confusion.

5. Input Validation Feedback


The interface includes built-in input validation to guide users in case of invalid
entries. If a user enters an incorrect data type (e.g., letters instead of numbers),
or if they attempt an invalid operation (like dividing by zero), the interface
will display an informative error message, such as:
- "Error! Division by zero is not allowed."
- "Invalid input! Please enter numeric values only."

These error messages are designed to be user-friendly, providing clear


instructions to help users correct their mistakes and proceed with
their calculations.

6. Exit and Restart Options


The user interface allows for a smooth exit from the program. At any time, the
user can choose to stop the calculator by typing a specific command (e.g., "exit"
or "q"). Additionally, if the user wishes to reset the process (i.e., change their
operation after seeing the menu), they can easily restart the process without
having to terminate the program.

Page | 10
---

Page | 11
Here is a simple implementation of the menu-based interface:
def menu():
print("Welcome to the Python Calculator")
print("Select an operation:")
print("1. Addition") print("2.
Subtraction") print("3.
Multiplication") print("4.
Division") print("5.
Modulus") print("6.
Exponentiation") print("7.
Square Root") print("8. Exit")

def get_input():
while True:
try:
x = float(input("Enter the first number: "))
return x
except ValueError:
print("Invalid input! Please enter a valid number.")

def get_second_input():
while True:
try:
y = float(input("Enter the second number: "))
return y
except ValueError:
print("Invalid input! Please enter a valid number.")

This code provides a basic structure for the menu and input validation, ensuring
a user-friendly experience with clear prompts and error handling.

Page | 12
6. RUNNING THE CALCULATOR
The process of running the Python calculator involves several straightforward
steps that guide users through the calculation workflow. This section outlines
how users can effectively start, interact with, and exit the calculator application,
ensuring a smooth and efficient experience.

Page | 13
import math

def modulus(a, b):


return a % b

def exponent(a, b):


return a ** b

def square_root(a):
if a >= 0:
return math.sqrt(a)
else:
return "Error: Cannot calculate square root of a negative number"

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b != 0: return
a/b
else:
return "Error: Division by zero"

def menu():
print("\nWelcome to the Python Calculator")
print("Select an operation:")
print("1. Addition") print("2.
Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Modulus")
print("6. Exponentiation")
print("7. Square Root")
print("8. Exit")
Page | 14
def get_input():
while True:
try:
x = float(input("Enter the first number: "))
return x
except ValueError:
print("Invalid input! Please enter a valid number.")

def get_second_input():
while True:
try:
y = float(input("Enter the second number: "))
return y
except ValueError:
print("Invalid input! Please enter a valid number.")

def calculator():
while True:
menu()
choice = input("Enter choice (1-8): ")

if choice == '1':
x = get_input()
y = get_second_input()
print("Result:", add(x, y))
elif choice == '2':
x = get_input()
y = get_second_input()
print("Result:", subtract(x, y))
elif choice == '3':
x = get_input()
y = get_second_input()
print("Result:", multiply(x, y))

Page | 15
Page | 16
elif choice == '4': x =
get_input()
y = get_second_input()
print("Result:", divide(x, y))
elif choice == '5': x =
get_input()
y = get_second_input()
print("Result:", modulus(x, y))
elif choice == '6': x =
get_input()
y = get_second_input()
print("Result:", exponent(x, y))
elif choice == '7': x =
get_input()
print("Result:", square_root(x))
elif choice == '8':
print("Exiting the calculator. Goodbye!")
break
else:
print("Invalid input! Please select a valid operation.")

if name == " main ":


calculator()

OUTPUT

Page | 17
(output 1)

(output 2)

Page | 18
(output 3)
7. CONCLUSION
The Python calculator project demonstrates the practical application of basic
and advanced programming concepts in building a fully functional, user-
friendly calculator. By developing this project, we’ve explored key areas of
software development, including modular programming, input validation, error
handling, and the design of a command-line interface (CLI). The calculator not
only performs basic arithmetic operations but also supports advanced functions
like modulus, exponentiation, and square root calculations.

Key Takeaways:
1. Modular Design: One of the core strengths of this project is its modular
design, where each mathematical operation is encapsulated in its own
function. This modularity improves code readability, allows for easier
debugging, and makes future enhancements much simpler. For example,
if a new mathematical function needs to be added, it can be done
without affecting the existing functionality.
2. Error Handling and Input Validation: The project emphasizes the
importance of handling user input and managing potential errors
effectively. Ensuring that users can only input valid numbers prevents the
calculator from crashing, while custom error messages provide users
with guidance when they make mistakes, such as attempting to divide by
zero or input non-numeric data. These considerations improve the user
experience and demonstrate how software can be made more robust and
user-friendly.
3. Scalability: The calculator’s design makes it highly scalable. Although it
begins as a command-line tool, it is built in such a way that it can easily
be expanded in the future. Users can add more complex mathematical
functions, such as logarithms or trigonometric calculations, without
needing to restructure the existing code. Additionally, with the use of
Python libraries like tkinter or PyQt, the project can be transformed into
a Graphical User Interface (GUI) application, making it more interactive
and visually appealing.
4. Educational Value: This project serves as an excellent learning tool
for beginners and intermediate developers. It covers foundational
programming concepts like:
o Loops and Conditionals: To handle the flow of the calculator
and provide a continuous interaction until the user chooses to exit.
o Functions: To break down each calculation into separate,
reusable components.
Page | 19
o Libraries: To enhance functionality, particularly using
Python’s built-in math library for advanced mathematical
operations.
Additionally, this project is a great way to explore how real-world applications
work, even though the focus is on simplicity. By writing your own calculator,
you can understand how professional calculators handle user input, perform
operations, and manage errors. It also gives insights into how stack-based
systems (like the order of operations or handling operator precedence) might
work in a more advanced calculator or mathematical expression evaluator.
5. Real-World Application: Though simple, the calculator has
real-world utility, enabling users to perform calculations in an efficient,
error-free manner. This project can be further customized for specific
use cases, such as scientific or financial calculators, and can be adapted
to support complex workflows for niche requirements. For instance,
extending the calculator with additional features such as history
tracking or memory functions can make it even more practical.

Page | 20

You might also like