Calculator in Python

1. Introduction

This tutorial guides you through creating a simple calculator in Python. The calculator will be able to perform basic arithmetic operations: addition, subtraction, multiplication, and division. This example will demonstrate basic Python functions, input handling, and simple conditionals.

2. Program Steps

1. Define functions for each arithmetic operation.

2. Take user input for the numbers and the operation to be performed.

3. Use conditionals to call the appropriate function based on user input.

4. Display the result of the arithmetic operation.

3. Code Program

# Step 1: Defining functions for arithmetic operations

def add(x, y):
    """Add Function"""
    return x + y

def subtract(x, y):
    """Subtract Function"""
    return x - y

def multiply(x, y):
    """Multiply Function"""
    return x * y

def divide(x, y):
    """Divide Function"""
    if y == 0:
        return "Error! Division by zero."
    else:
        return x / y

# Step 2: Taking user input

print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice(1/2/3/4): ")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Step 3: Using conditionals to perform the selected operation

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))
else:
    print("Invalid Input")

Output:

Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4): 1
Enter first number: 5
Enter second number: 3
5.0 + 3.0 = 8.0

Explanation:

1. The program starts by defining four functions: add, subtract, multiply, and divide, each performing the corresponding arithmetic operation.

2. It then prints the options available to the user and takes their input for both the operation (as a choice between 1 and 4) and the two numbers on which the operation will be performed.

3. Based on the operation selected by the user (stored in the choice variable), the program uses a series of if-elif statements to call the appropriate function and pass the user-provided numbers as arguments.

4. Each function returns the result of the arithmetic operation, which is then printed to the console.

5. For division, there's an additional check to prevent division by zero, returning an error message if y == 0.

Comments