Table of contents
- Step 1: Setting Up the Environment
- Step 2: Creating the Python File
- Step 3: Understanding the Code
- Step 4: Implementing User Interaction
- Step 5: Processing User Input
- Step 6: Executing the Operation
- Step 7: Handling Invalid Input
- Step 8: Running the Program
- Step 9: Using the Simple Calculator
- Sample Solution (in case you get stuck):
In this tutorial, I will walk you through building a simple command-line calculator program in Python. This program will allow the user to perform basic mathematical operations like addition, subtraction, multiplication, and division on two numbers.
Step 1: Setting Up the Environment
To get started, open your favorite text editor or integrated development environment (IDE) where you prefer to write Python code.
Step 2: Creating the Python File
Create a new file and save it as calculator.py
and add the following code:
# calculator.py
# This is a simple calculator program.
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
if num2 != 0:
return num1 / num2
else:
return "Error: Division by zero"
print("Simple Calculator")
print("------------------")
Step 3: Understanding the Code
Before we proceed, let's take a moment to understand the code provided above:
We have defined four functions:
add
,subtract
,multiply
, anddivide
, which will perform the corresponding mathematical operations on two numbers.Each function takes two arguments (
num1
andnum2
) and returns the result of the operation.The
divide
function has an additional check to prevent division by zero. If thenum2
is 0, it will return an error message.
Step 4: Implementing User Interaction
Let's add code to allow user interaction and perform the desired operations:
while True:
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
In this section, we've created an infinite loop that keeps running until the user chooses to exit (choice == '5'
).
Step 5: Processing User Input
Now, let's handle the user's choice and perform the selected operation:
if choice == '5':
print("Goodbye!")
break
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
If the user chooses 5
, the program will break out of the loop and terminate. Otherwise, it will prompt the user to enter two numbers on which the operation will be applied.
Step 6: Executing the Operation
Next, we'll execute the selected operation based on the user's choice:
if choice == '1':
result = add(num1, num2)
print(f"The sum of {num1} and {num2} is {result}")
elif choice == '2':
result = subtract(num1, num2)
print(f"The difference between {num1} and {num2} is {result}")
elif choice == '3':
result = multiply(num1, num2)
print(f"The product of {num1} and {num2} is {result}")
elif choice == '4':
result = divide(num1, num2)
print(f"The division of {num1} by {num2} is {result}")
else:
print("Invalid input. Please try again.")
Here, we use if-elif-else
statements to determine the user's choice and perform the corresponding operation. The result is then displayed on the screen.
Step 7: Handling Invalid Input
Lastly, we will handle the case when the user enters an invalid option:
else:
print("Invalid input. Please try again.")
If the user enters an option other than 1 to 5, the program will inform them that their input is invalid and prompt them to try again.
Step 8: Running the Program
Save the calculator.py
file and open your command line or terminal. Navigate to the location where you saved the file and run the program with the following command:
python calculator.py
Step 9: Using the Simple Calculator
After running the program, you will see the title line "Simple Calculator" displayed on the screen. The program will offer a list of available operations and prompt you to make a choice by entering a number from 1 to 5.
Enter
5
to exit the program, and it will display "Goodbye!" before terminating.For the other options (1 to 4), the program will prompt you to enter the two numbers on which the selected operation should be applied.
After performing the operation, the program will return to the menu and prompt you to select another operation.
Congratulations! You have successfully created a simple calculator program in Python that allows users to perform basic mathematical operations. Feel free to further enhance the program or add more functionalities to suit your needs. Happy coding!
Sample Solution (in case you get stuck):
# This is a simple calculator program.
# Function to add two numbers
def add(num1, num2):
return num1 + num2
# function to subtract two numbers
def subtract(num1, num2):
return num1 - num2
# function to multiply two numbers
def multiply(num1, num2):
return num1 * num2
# function to divide two numbers, handles division by zero
def divide(num1, num2):
if num2 != 0:
return num1 / num2
else:
return "Error: division by zero"
# prints the title of the calculator
print("Simple calculator")
print("------------------")
# Start an infinite loop for user interaction
while True:
# print the available operations
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. divide")
print("5. Exit")
# prompt the user to enter his choice
choice = input("Enter a choice (1-5): ")
# Check if the user wants to exit
if choice == '5':
print("Goodbye!")
break
# prompt the user to enter the two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Execute the selected operation based on the user's choice
if choice == '1':
result = add(num1, num2)
print(f "The sum of {num1} and {num2} is {result}")
elif choice == '2':
result = subtraction(num1, num2)
print(f "The difference between {num1} and {num2} is {result}")
elif choice == '3':
result = multiplication(num1, num2)
print(f "The product of {num1} and {num2} is {result}")
elif choice == '4':
result = divide(num1, num2)
print(f "The division of {num1} by {num2} is {result}")
else:
print("Invalid input, please try again.")