This project implements a simple command-line calculator in Python that performs basic arithmetic operations on two numbers.
The calculator is designed to demonstrate the use of Python functions, dictionaries, loops, and user input handling.
The program allows users to perform calculations continuously by using the result of the previous operation as the starting number for the next calculation.
Create a calculator program that allows the user to perform mathematical operations on two numbers using basic functions and a dictionary to store the operations.
The program should also allow users to continue calculations using the result of previous calculations.
The calculator program follows these steps:
-
Create four basic mathematical functions:
addsubtractmultiplydivide
Each function takes two numbers as input and returns the result of the operation.
-
Create a dictionary called
operationsthat maps operation symbols to their corresponding functions. -
Create a function called
calculatorthat prompts the user to input the first number. -
Use a
forloop to display the available operation symbols. -
Create a
whileloop that continues running until the user chooses to end the calculation. -
Inside the loop:
- Prompt the user to select an operation symbol.
- Prompt the user to input the second number.
-
Use the dictionary to retrieve the function that corresponds to the selected operation symbol and store it in a variable called
calculation_function. -
Perform the calculation by calling the selected function on the two numbers and store the result in a variable called
answer. -
Print the equation and the result of the calculation.
-
Ask the user if they would like to continue using the result as the first number for further calculations.
-
If the user chooses to continue, update the
first_numbervariable to the value ofanswer. -
If the user chooses to start a new calculation, request a new first number.
- Basic arithmetic operations
- Continuous calculations using previous results
- Command-line interaction
- Error handling for invalid operations
- Python
Clone the repository
git clone https://github.com/victoruzoe/python-calculator-cli
Navigate to the project
cd python-calculator-cli
Run the program
python calculator.py
Enter the first number: 10 Choose an operation: + Enter the second number: 5
Output: 10 + 5 = 15
