TechTorch

Location:HOME > Technology > content

Technology

Guide to Writing a Python Program That Divides and Adds Numbers

January 30, 2025Technology1801
Guide to Writing a Python Program That Divides and Adds Numbers Python

Guide to Writing a Python Program That Divides and Adds Numbers

Python is a powerful and versatile programming language that offers simplicity and readability. In this guide, we will explore how to write a Python program that prompts for three numbers, divides the first number by the second, and adds the result to the third number. This task provides a great introduction to user input and basic arithmetic operations in Python.

User Input for Three Numbers

To begin, we will use the input function to gather three numbers from the user. The float function is used to convert these inputs into floating-point numbers, allowing for the inclusion of decimal values. Here's a sample program to accomplish this task:

num1  float(input("Enter the first number: "))
num2  float(input("Enter the second number: "))
num3  float(input("Enter the third number: "))

Handling Division by Zero

Division by zero is a common error in programming. To avoid this, we need to include a check to ensure that the second number is not zero before performing the division. Here is the complete program:

num1  float(input("Enter the first number: "))
num2  float(input("Enter the second number: "))
num3  float(input("Enter the third number: "))
division_result  None
if num2 ! 0:
    division_result  num1 / num2
    final_result  division_result   num3
else:
    print("Error: Division by zero is not allowed.")
print("Final result:", final_result)

In this program, we first attempt to divide num1 by num2. If num2 is not zero, the result is stored in division_result. This result is then added to num3 and stored in final_result. If num2 is zero, the program prints an error message.

Running the Program

This program can be run in any Python environment. Just ensure that you handle the case where the second number is zero to avoid runtime errors. The program should work correctly for both Python 2.x and 3.x, with some syntactical differences.

Testing the Program

Here is an example of how you might test the program:

import unittest
def get_number(numbers: str) - float:
    num_list  numbers.split()
    division_result  (float(num_list[0]) / float(num_list[1]))   float(num_list[2])
    return division_result
class TestCases(unittest.TestCase):
    def test_one(self):
        (get_number('12 4 2'), 5.0)
def main():
    ()
if __name__  '__main__':
    main()

In this test case, we verify that the program correctly handles the division and addition of the numbers. The unittest framework is used to define a test case and run it.