Code Overview Thesis

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Code Overview

This code implements a simple command-line calculator that can perform basic arithmetic operations
(addition, subtraction, multiplication, and division) with both integer and decimal inputs. Additionally, it
allows the user to perform multiple calculations in one run.

Detailed Breakdown

1. Function Definitions for Arithmetic Operations:

python

Copy code

def add(x, y):

"""This function adds two numbers."""

return x + y

def subtract(x, y):

"""This function subtracts two numbers."""

return x - y

def multiply(x, y):

"""This function multiplies two numbers."""

return x * y

def divide(x, y):

"""This function divides two numbers."""

if y == 0:

return "Error! Division by zero."

return x / y

o Purpose: These functions (add, subtract, multiply, and divide) perform basic arithmetic
operations. Each function takes two parameters (x and y) and returns the result of the
operation.

o Division Handling: The divide function includes a check to prevent division by zero,
returning an error message instead of raising an exception.
2. Function to Get User's Operation Choice:

python

Copy code

def get_operation():

print("Hello! Select the operation that you want to use.")

print("1. Addition")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

while True:

choice = input("Enter choice (1/2/3/4): ")

if choice in ['1', '2', '3', '4']:

return choice

else:

print("Invalid choice! Please select a valid operation (1/2/3/4).")

o Purpose: This function prompts the user to select an arithmetic operation. It prints the
available options and continues to request input until the user enters a valid choice (1 to
4).

3. Function to Get Valid Number Input:

python

Copy code

def get_number(prompt):

while True:

try:

return float(input(prompt))

except ValueError:

print("Invalid input! Please enter a valid number (integer or decimal).")


o Purpose: This function asks the user for a number and attempts to convert the input to a
float, which allows for both integer and decimal inputs. If the input is invalid (e.g., not a
number), it catches the ValueError and prompts the user again.

4. Main Calculator Logic:

python

Copy code

def calculator():

operation = get_operation() # Get the chosen operation

num1 = get_number("Enter first number: ") # Get the first number

num2 = get_number("Enter second number: ") # Get the second number

# Perform the selected operation and display the result

if operation == '1':

result = add(num1, num2)

elif operation == '2':

result = subtract(num1, num2)

elif operation == '3':

result = multiply(num1, num2)

elif operation == '4':

result = divide(num1, num2)

# Output result

if operation in ['1', '2', '3']: # If operation is addition, subtraction, or multiplication

if num1.is_integer() and num2.is_integer():

result = int(result) # Convert the result to an integer if both inputs are integers

print(f"Result: {result}")

o Purpose: This is the main function that orchestrates the flow of the calculator. It calls the
get_operation and get_number functions to gather user inputs, performs the selected
arithmetic operation, and displays the result.
o Result Conversion: If the operation is addition, subtraction, or multiplication and both
inputs are integers, the result is converted to an integer before printing.

5. Function to Ask User if They Want to Calculate Again:

python

Copy code

def again():

calc_again = input('''Do you want to calculate again?

Please type Y for YES or N for NO.

''')

if calc_again.upper() == 'Y':

calculator()

elif calc_again.upper() == 'N':

print('See you later.')

else:

again()

o Purpose: This function prompts the user to decide whether they want to perform
another calculation. If the user types "Y", the calculator function is called again; if they
type "N", a goodbye message is printed. If the input is invalid, it calls itself recursively
until valid input is received.

6. Running the Calculator:

python

Copy code

calculator() # Run the calculator program

o Purpose: This line starts the entire calculator program by calling the calculator function
for the first time.

Summary

 Functionality: The program allows users to perform basic arithmetic calculations, handle both
integers and decimals, and manage multiple calculations in a single session.

 User Interaction: It employs loops and error handling to create a user-friendly experience,
ensuring that the program does not crash due to invalid inputs and allows users to continue
calculating as desired.
 Modularity: The structure is modular, meaning each function has a single responsibility, making
the code easier to understand and maintain.

This calculator is a practical example of applying programming concepts like functions, user input
handling, and control flow in Python.

You might also like