Brief: Write a Python program to add two numbers. It provides a step-by-step guide on how to write a program that prompts the user to enter two numbers, adds them together, and displays the result.

Python is a popular programming language known for its simplicity and ease of use. One of the fundamental concepts in any programming language is arithmetic operations, such as addition, subtraction, multiplication, and division. In this article, we will discuss how to write a Python program to add two numbers.

Adding Two Numbers in Python

Adding two numbers in Python is a straightforward task. You can use the operator to add two numbers. Here’s a simple example:

# Take user input for two numbers

num1 = float(input(“Enter first number: “))

num2 = float(input(“Enter second number: “))

# Add the two numbers

sum = num1 num2

# Display the result

print(“The sum of {} and {} is {}”.format(num1, num2, sum))

In this program, we first take user input for two numbers using the input() function. Since we want to perform arithmetic operations, we convert the input to float type using the float() function.

Next, we add the two numbers using the operator and store the result in the variable sum.


Finally, we display the result using the print() function. We use string formatting to print the original numbers and the sum in a readable format.

Let’s run this program with some sample input:

Execution result:

Enter first number: 10.5 Enter second number: 20.3 The sum of 10.5 and 20.3 is 30.8

As you can see, the program correctly calculates the sum of two numbers.

Adding Numbers from a List

There are other ways to add two numbers in Python as well. For example, you can use the sum() function to add a list of numbers. Here’s an example:

# Define a list of numbers

numbers = [10, 20, 30]

# Add the numbers using the sum() function

total = sum(numbers)

# Display the result

print(“The sum of {} is {}”.format(numbers, total))

In this program, we define a list of numbers and use the sum() function to add them. Finally, we display the result using string formatting.

Let’s run this program:

Execution result:

The sum of [10, 20, 30] is 60

As you can see, the sum() function correctly calculates the sum of the numbers in the list.

Conclusion

In conclusion, adding two numbers in Python is a simple task that can be accomplished using the operator or the sum() function. By understanding the basic arithmetic operations in Python, you can begin to build more complex programs that perform mathematical computations.