Welcome to the Python Calculator tutorial! This guide will walk you through creating a simple calculator using Python. 🧮
🛠️ Step-by-Step Guide
1. Set Up Your Environment
Start by ensuring Python is installed on your system. You can check this by running:
python --version
If you need help installing Python, visit our Python Basics tutorial.
2. Basic Arithmetic Operations
Create a script to handle addition, subtraction, multiplication, and division:
def calculate(operation, num1, num2):
if operation == '+':
return num1 + num2
elif operation == '-':
return num1 - num2
elif operation == '*':
return num1 * num2
elif operation == '/':
return num1 / num2
else:
return "Invalid operation"
# Example usage
result = calculate('+', 5, 3)
print(result)
3. User Input Handling
Modify the code to accept user input via the command line:
operation = input("Enter operation (+, -, *, /): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
4. Error Handling
Add checks for division by zero and invalid inputs:
if num2 == 0 and operation == '/':
return "Division by zero is not allowed"
5. Expand Functionality
Enhance your calculator with advanced features like exponentiation or modulo:
elif operation == '**':
return num1 ** num2
elif operation == '%':
return num1 % num2
📘 Further Learning
For more Python projects, check out our Python Data Structures tutorial. Happy coding! 🚀