Crafting a Simple Calculator Program in Python
Introduction:
With its simplicity and readability, Python is an excellent language for beginners to start their programming journey. One of the first projects often tackled by aspiring Python programmers is creating a simple calculator program. In this tutorial, we'll walk through the steps to create a basic calculator in Python, covering addition, subtraction, multiplication, and division operations.
Getting Started:
Before diving into the code, make sure you have Python installed on your system. You can download and install Python from the official website (https://www.python.org/) if you haven't already.
Creating the Calculator Program:
Let's start by opening your favorite text editor or integrated development environment (IDE) to write our Python code. Follow along as we create the calculator program step by step:
# Define a function for addition operation
def add(x, y):
return x + y
# Define a function for subtraction operation
def subtract(x, y):
return x - y
# Define a function for a multiplication operation
def multiply(x, y):
return x * y
# Define a function for division operation
def divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y
# Main function to execute the calculator program
def main():
print("Welcome to Simple Calculator")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
# Take input from the user
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid input")
# Call the main function to run the program
if __name__ == "__main__":
main()
Understanding the Code:
- We define four functions for addition, subtraction, multiplication, and division operations.
- The `main()` function serves as the entry point of our program, displaying a menu of operations for the user to choose from.
- Based on the user's choice, the program prompts the user to enter two numbers and performs the selected operation.
Running the Program:
Save the code in a file with a `.py` extension, such as `calculator.py`. Open a terminal or command prompt, navigate to the file's directory, and execute the program by typing `python calculator.py`.
Conclusion:
Congratulations! You've just created a simple calculator program in Python. This project is a great way to practice fundamental Python concepts such as functions, user input, and conditional statements.
Comments
Post a Comment