Congratulations on getting started with Python! Let’s now build your first project: a Simple Calculator. This project will teach you how to interact with users, perform basic calculations, and organize your code into functions.
You will create a Python program that:
Understanding the problem and planning your code is essential. Here’s what your calculator needs:
Open your editor and create a new file named calculator.py
. Add the following code:
# Simple Calculator in Python
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero is not allowed."
return a / b
print("Welcome to the Simple Calculator!")
print("Select an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = input("Enter the number of your choice (1/2/3/4): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
print("The result is:", add(num1, num2))
elif choice == '2':
print("The result is:", subtract(num1, num2))
elif choice == '3':
print("The result is:", multiply(num1, num2))
elif choice == '4':
print("The result is:", divide(num1, num2))
else:
print("Invalid choice. Please run the program again.")
calculator.py
.python calculator.py
Always validate user inputs to prevent errors like dividing by zero or entering invalid numbers.
Functions:
Each mathematical operation (add, subtract, multiply, divide) is defined in a separate function for modularity.
Input and Output:
input
function.float
to handle decimal numbers.Decision Making:
The program uses if-elif-else
statements to perform the operation based on the user's choice.