Python Program: Arithmetical Operations
In this blog post, we’ll delve into a Python program that performs various arithmetical operations. We’ll discuss the algorithm, provide a step-by-step explanation, present the Python code, and include examples with outputs.
Understanding the Algorithm
The algorithm for arithmetical operations involves the following steps:
Input Numbers: Take two numbers as input.
Addition: Add the two input numbers.
Subtraction: Subtract the second number from the first.
Multiplication: Multiply the two input numbers.
Division: Divide the first number by the second (avoiding division by zero).
Output Results: Display the results of all operations.
Python Program for Arithmetical Operations
Let’s implement the algorithm in a Python program:
def perform_arithmetical_operations(num1, num2):
# Addition
addition_result = num1 + num2
# Subtraction
subtraction_result = num1 - num2
# Multiplication
multiplication_result = num1 * num2
# Division (avoiding division by zero)
division_result = num1 / num2 if num2 != 0 else "Cannot divide by zero"
return addition_result, subtraction_result, multiplication_result, division_result
# Input two numbers
number1 = float(input("Enter the first number: "))
number2 = float(input("Enter the second number: "))
# Perform arithmetical operations
results = perform_arithmetical_operations(number1, number2)
# Display results
print(f"Addition Result: {results[0]}")
print(f"Subtraction Result: {results[1]}")
print(f"Multiplication Result: {results[2]}")
print(f"Division Result: {results[3]}")
Output Example
Example: Arithmetical Operations
Let’s input the numbers 5
and 2
:
Input
Enter the first number: 5
Enter the second number: 2
Output
Addition Result: 7.0
Subtraction Result: 3.0
Multiplication Result: 10.0
Division Result: 2.5
Explanation
The program defines a function perform_arithmetical_operations
that takes two numbers as parameters and returns the results of addition, subtraction, multiplication, and division. It then takes user input for two numbers, calls the function with the input values, and prints the results.
Conclusion
This Python program demonstrates the implementation of basic arithmetical operations. Understanding and implementing such operations are fundamental for building more complex algorithms and applications in Python. Feel free to modify the program to suit your needs or extend it for additional operations.
If you have any questions or want to explore more Python programming topics, don’t hesitate to ask!