Hi everyone, my name is Iz Zahira Binti Ramlee.
Today, I’ll show you how to create a simple calculator
using Python. This calculator will handle basic operations like addition, subtraction, multiplication,
and division. Let’s get started!
Step 1: Define the Arithmetic Functions
"Breaking each arithmetic operation into its own procedure makes your code easier to maintain. If
the logic for any operation needs to change, you can update just one function without affecting the
entire program.”
Now, let’s create four functions to handle the arithmetic operations.
First, define the four basic arithmetic functions. Start with add() to add two numbers. Use this code:
def add(x, y):
return x + y
Next, define subtract() to subtract the second number from the first. Write this:
def subtract(x, y):
return x – y
Then, create multiply() to multiply two numbers together:
def multiply(x, y):
return x * y
Lastly, define divide() to divide two numbers. Add a check to prevent dividing by zero:
def divide(x, y):
if y == 0:
return 'Cannot divide by zero'
return x / y
These functions will handle the basic operations of your calculator.
Step 2: Create the Display Menu
Next, create a display_menu() function to show the options to the user. Use this code:
def display_menu():
print('\\nSelect operation:')
print('1. Add')
print('2. Subtract')
print('3. Multiply')
print('4. Divide')
print('5. Exit')
This procedure is essential because it simplifies how the program presents options to the user.
Instead of writing the menu multiple times, you can call this function anytime the user needs to
make a choice(this function will present the available choices for the user to select from). This will
make it easier for the user to select which calculation they want to perform.
Step 3: Capture User Input
Now, create a function get_choice() to capture the user’s operation choice. Write this:
def get_choice():
return input('\\nEnter choice (1/2/3/4/5): ')
Next, write the get_numbers() function to get two numbers from the user. Add input validation to
handle errors:
def get_numbers():
while True:
try:
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
return num1, num2
except ValueError:
print('Invalid input! Please enter numbers only.')
These functions ensure you get both the operation and numbers correctly from the user.
Step 4: Write the Main Calculator Logic
This procedure acts as the 'control center' of your program. It integrates all other procedures,
showing the power of modularity. By calling different procedures based on user input, it makes the
code organized and flexible.
finally, create the main function calculator() to handle everything. Write this code:
def calculator():
while True:
display_menu() # Show the menu
choice = get_choice() # Get the user’s choice
if choice == '5': # Exit condition
print('Exiting the calculator.')
break
if choice in ['1', '2', '3', '4']:
num1, num2 = get_numbers() # Get two numbers from the user
# Perform the operation based on the choice
if choice == '1':
print(f'The result is: {add(num1, num2)}')
elif choice == '2':
print(f'The result is: {subtract(num1, num2)}')
elif choice == '3':
print(f'The result is: {multiply(num1, num2)}')
elif choice == '4':
print(f'The result is: {divide(num1, num2)}')
else:
print('Invalid input! Please select a valid operation.')
This loop keeps the calculator running until the user decides to exit, and performs the appropriate
operation based on the user’s choice.
And that’s it! We’ve created a simple calculator using Python in just a few minutes. You can expand
on this by adding more features or refining the user interface. Thanks for watching, and happy
coding!
Values:
1. Use the while loop to keep the calculator running until the user exits.
2. Error handling: Make sure to handle invalid inputs and avoid division by zero.