Project : Basic Calculator in Python
To develop a Basic Calculator in Python you need to follow these steps. This calculator consist with addition, subtraction, multiplication, and division, input validation and error handling.
Step 1: Define the Main Structure
The main structure is defined as follow : The Basic calculator in Python will:
- First, take two numbers as input.
- Then, take an operator (+, -, *, /) as input.
- It performs the calculation based on the operator.
- Then.display the result.
- Allow the user to perform multiple calculations or exit.
Step 2: Create a Function to Get Valid Numbers
A function is defined to ensure the user enters valid numbers. If the input is invalid (e.g., a string), the program will prompt the user to try again.Python Code
Python Code
def get_number(prompt):
while True:
try:
num = float(input(prompt)) # Convert input to a float
return num
except ValueError:
print("Invalid input. Please enter a number.")
Explanation:
The input() function takes user input. float() converts the input to a floating-point number. If the input is not a valid number, a ValueError occurs, and the program asks the user to try again.
Step 3: Create a Function to Get a Valid Operator
We need a function to ensure the user enters a valid operator (+, -, *, /).
Python Code
def get_operator():
while True:
op = input("Enter operator (+, -, *, /): ")
if op in ['+', '-', '*', '/']: # Check if the operator is valid
return op
print("Invalid operator. Please enter +, -, *, or /.")
Explanation:
The program checks if the entered operator is one of the allowed operators. If it does not meet the condition, it prompts the user to try again.
Step 4: Handle Division by Zero
For division, we need to ensure the second number is not zero to avoid errors.
Python Code
def get_second_number(operator):
while True:
try:
num = float(input("Enter second number: "))
if operator == '/' and num == 0: # Check for division by zero
print("Error: Division by zero is not allowed.")
continue
return num
except ValueError:
print("Invalid input. Please enter a number.")
Explanation:
If the operator is / and the second number is 0, the program displays an error message and asks for the number again.
Step 5: Format the Output
To make the output user-friendly, we’ll format numbers to display as integers if they are whole numbers like 5.0 becomes 5, 7.0 becomes 7 so on.
Python Code
def format_number(num):
if isinstance(num, float) and num.is_integer(): # Check if the number is a whole number
return str(int(num)) # Convert to integer and then to string
return str(num) # Otherwise, return as a string
Explanation:
The is_integer() keyword checks if the float is a whole number. If the condition is true, the number is converted to an integer and then to a string for display.
Step 6: Perform the Calculation
Based on the operator, the program will perform the corresponding calculation.
Python Code
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
Explanation:
The program uses conditional statements (if, elif) to determine which operation to perform.
Step 7: Display the Result
After performing the calculation, It will display the result in a user-friendly format.
Python Code
num1_str = format_number(num1)
num2_str = format_number(num2)
result_str = format_number(result)
print(f"Result: {num1_str} {operator} {num2_str} = {result_str}")
Explanation:
The format_number() function confirms the numbers are displayed correctly. The result is displayed using an f-string for clarity.
Step 8: Allow Multiple Calculations
The program will ask the user if they want to perform another calculation or exit.
Python Code
another = input("Would you like to perform another calculation? (yes/no): ").lower()
if another not in ['yes', 'y']:
print("Goodbye!")
break
Explanation:
The program checks if the user wants to continue. If the user enters anything other than yes or y, the program exits.
The Complete Code is below :
Python Code
def get_number(prompt):
while True:
try:
num = float(input(prompt))
return num
except ValueError:
print("Invalid input. Please enter a number.")
def get_operator():
while True:
op = input("Enter operator (+, -, *, /): ")
if op in ['+', '-', '*', '/']:
return op
print("Invalid operator. Please enter +, -, *, or /.")
def get_second_number(operator):
while True:
try:
num = float(input("Enter second number: "))
if operator == '/' and num == 0:
print("Error: Division by zero is not allowed.")
continue
return num
except ValueError:
print("Invalid input. Please enter a number.")
def format_number(num):
if isinstance(num, float) and num.is_integer():
return str(int(num))
return str(num)
print("Welcome to the Basic Calculator!")
print("You can perform addition, subtraction, multiplication, and division.")
while True:
num1 = get_number("Enter the first number: ")
operator = get_operator()
num2 = get_second_number(operator)
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
num1_str = format_number(num1)
num2_str = format_number(num2)
result_str = format_number(result)
print(f"Result: {num1_str} {operator} {num2_str} = {result_str}")
another = input("Would you like to perform another calculation? (yes/no): ").lower()
if another not in ['yes', 'y']:
print("Goodbye!")
break
Python Output
Welcome to the Basic Calculator!
You can perform addition, subtraction, multiplication, and division.
Enter the first number: 10
Enter operator (+, -, *, /): *
Enter second number: 5
Result: 10 * 5 = 50
Would you like to perform another calculation? (yes/no): no
Goodbye!