Creating a basic calculator in Python is a popular beginner project that offers a hands-on approach to familiarize oneself with fundamental coding concepts. But as one progresses in the world of programming, it becomes intriguing to enhance basic applications with advanced functionalities.
In this guide, we’ll first outline how to make a simple calculator in Python. Next, we’ll enhance this basic calculator to remember its previous result, allowing users to continue calculations from where they left off or start anew.
The Program
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Undefined (division by zero)"
return x / y
def main():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
if choice not in ('1', '2', '3', '4'):
print("Invalid input")
return
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
if __name__ == "__main__":
main()
Breaking Down the Code
- Function Definitions:
- add(x, y): Takes two parameters and returns their sum.
- subtract(x, y): Returns the result of subtracting y from x.
- multiply(x, y): Returns the product of x and y.
- divide(x, y): Checks if y is zero to avoid division by zero error, and if not, returns the result of dividing x by y.
- Main Function:
This function drives the calculator.
- First, it displays a menu to the user, offering four basic operations.
- `choice` variable: Takes user input to decide the operation.
- We check if the entered choice is valid (i.e., among the 4 given options). If not, it displays an error message.
- `num1` and `num2` variables: Take input numbers from the user. We use the `float()` function to allow decimal inputs.
- Depending on the chosen operation, the respective function is called and the result is displayed.
- if __name__ == “__main__”::
This line checks if the script is being run as the main program. If it is, it calls the `main()` function to start the calculator. This ensures that if this code is imported elsewhere as a module, it won’t automatically run the calculator.
Enhanced Version Calculator Program
Here’s an enhanced version of the calculator that remembers previous values and allows operations on them. We’ll also add a clear function to reset the calculator:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Undefined (division by zero)"
return x / y
def main():
previous_result = None
while True:
if previous_result is not None:
cont = input(f"Continue with previous result {previous_result} (y/n): ").lower()
if cont == 'y':
num1 = previous_result
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
else:
previous_result = None
continue
else:
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
choice = input("Enter choice (1/2/3/4/5): ")
if choice == '5':
print("Exiting calculator...")
break
if choice not in ('1', '2', '3', '4'):
print("Invalid input")
continue
if previous_result is None:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = add(num1, num2)
print(num1, "+", num2, "=", result)
elif choice == '2':
result = subtract(num1, num2)
print(num1, "-", num2, "=", result)
elif choice == '3':
result = multiply(num1, num2)
print(num1, "*", num2, "=", result)
elif choice == '4':
result = divide(num1, num2)
print(num1, "/", num2, "=", result)
previous_result = result
if __name__ == "__main__":
main()
Explanation:
- The calculator first checks if there’s a previous_result available. If yes, it asks the user whether they want to continue with the previous result. If the user answers with ‘y’, it only asks for the operation and the second number.
- If the user answers with ‘n’, or if there’s no previous result available, the full menu (without the options to use or clear the previous result) is shown.
- If the user selects the exit option, the calculator closes.
Conclusion
Through these two calculator versions, we’ve journeyed from creating a fundamental Python program to enhancing it with a more user-centric feature. The basic calculator provides a solid foundation for understanding essential programming constructs like functions, loops, and conditionals. The advanced version builds upon this foundation, introducing a more dynamic user interaction by remembering previous calculations. This feature can be particularly useful for users who want to carry out a series of calculations.
Moreover, the advanced version showcases how even simple applications can benefit from iterative improvements, enhancing user experience. It’s a testament to Python’s versatility and how it caters to both foundational learning and advanced application development. As next steps, one can further extend these projects, for example, by introducing complex mathematical functions or even incorporating a graphical user interface (GUI).