Python program to do arithmetical operations

Created with Sketch.

Python Program for Arithmetical Operations

Introduction

In this Python program, we will create a simple calculator that performs basic arithmetical operations such as addition, subtraction, multiplication, and division. The user can input two numbers and choose the operation they want to perform. We will discuss the algorithm, provide the Python code, and explain how the program works.

Understanding the Algorithm

The algorithm for the arithmetical operations program involves the following steps:

  1. Input: Accept two numbers and the desired operation from the user.
  2. Perform Operation: Use conditional statements to determine the selected operation and perform the corresponding arithmetic calculation.
  3. Display Result: Print or display the result of the arithmetic operation.

Python Program for Arithmetical Operations

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 x / y
    else:
        return "Cannot divide by zero."

# Input: Get numbers and operation from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Choose operation (+, -, *, /): ")

# Perform the selected operation
result = 0
if operation == '+':
    result = add(num1, num2)
elif operation == '-':
    result = subtract(num1, num2)
elif operation == '*':
    result = multiply(num1, num2)
elif operation == '/':
    result = divide(num1, num2)
else:
    print("Invalid operation. Please choose +, -, *, /.")

# Display the result
print(f"Result: {result}")

Output Example

Example: Perform Addition

Enter the first number: 10
Enter the second number: 5
Choose operation (+, -, *, /): +
Result: 15.0

Example: Perform Division

 
Enter the first number: 8
Enter the second number: 2
Choose operation (+, -, *, /): /
Result: 4.0

Explanation

The Python program defines functions for addition, subtraction, multiplication, and division. It then prompts the user to input two numbers and the desired arithmetic operation. The program uses conditional statements to determine the selected operation and calls the corresponding function to perform the calculation. The result is then displayed.

In the provided examples, the user inputs two numbers and chooses either addition or division. The program calculates and displays the results accordingly.

Conclusion

This Python program serves as a basic arithmetical calculator, allowing users to perform addition, subtraction, multiplication, and division on two numbers. You can customize and expand this program to include additional operations or features.

If you have any questions or need further clarification, feel free to ask!

Leave a Reply

Your email address will not be published. Required fields are marked *