Python Program to Add Two Numbers

Updated on December 6, 2024
Add two numbers header image

Introduction

Adding two numbers is a fundamental task in any programming language, serving as a common starting point for new learners to understand syntax and operations. Python, with its clean and straightforward syntax, offers a user-friendly way to handle basic arithmetic operations like addition.

In this article, you will learn how to add two numbers using Python. The discussion includes examples using literals, variables, and user inputs, illustrating different scenarios where number addition becomes necessary.

Adding Numbers Using Literals

Direct Addition of Two Numbers

  1. Open your Python editor or an interactive shell.

  2. Type the direct addition of two values.

    python
    result = 3 + 2
    print(result)
    

    The code above directly adds the numbers 3 and 2, storing the result in the variable result. The print() function then outputs the result, which is 5.

Adding Numbers Stored in Variables

Basic Variable Addition

  1. Define variables to store your numbers.

  2. Perform addition using these variables.

    python
    num1 = 5
    num2 = 7
    sum = num1 + num2
    print(sum)
    

    This example stores the numbers 5 and 7 in num1 and num2 respectively. The addition is performed, and the result (12) is stored in the variable sum, which is then printed.

Using User Input to Add Numbers

Addition of Two Numbers from User Input

  1. Use the input() function to gather numbers from the user.

  2. Convert the string inputs to integers.

  3. Add the numbers and display the result.

    python
    first_number = int(input("Enter the first number: "))
    second_number = int(input("Enter the second number: "))
    total = first_number + second_number
    print("The sum of the numbers is:", total)
    

    In the script above, input() collects string data from the user, which is then converted to integers using int(). The integers are added together and the sum is displayed. This method allows dynamic input from users at runtime.

Conclusion

Python provides a simple and efficient framework for performing basic arithmetic operations such as adding two numbers. Whether you're dealing with hardcoded values, variables, or user inputs, Python's easy-to-understand syntax makes these tasks straightforward. Following these examples, enable yourself to handle basic number manipulation in your applications, paving the way for more complex programming tasks.