Table of contents

Python Program to add two numbers

Write a Python program that takes two numbers as input from the user and outputs their sum.

Input-Output Examples

Example 1:

  • Input:
    Enter first number: 5
    Enter second number: 10
  • Output:
    The sum of 5 and 10 is: 15

Example 2:

  • Input:
    Enter first number: -4
    Enter second number: 9
  • Output:
    The sum of -4 and 9 is: 5

Algorithm to add two numbers

  1. Start
  2. Take input: Prompt the user to enter the first number (num1).
  3. Take input: Prompt the user to enter the second number (num2).
  4. Add the numbers: Compute the sum of num1 and num2 and store the result in the variable sum.
  5. Display the result: Print the value of sum.
  6. End

Python Program to add two numbers

python
# Python program to add two numbers

# Take input from the user for the first number
num1 = int(input("Enter the first number: "))

# Take input from the user for the second number
num2 = int(input("Enter the second number: "))

# Add the two numbers
sum = num1 + num2

# Display the result
print(f"The sum of {num1} and {num2} is: {sum}")

Code Explanation

  1. Taking input from the user:
    The input() function is used to take input from the user. Since input() returns data as a string, we convert it to an integer using the int() function so that mathematical operations can be performed. In the above code, num1 and num2 store the two numbers provided by the user.
  2. Adding the numbers:
    Once we have the two numbers, the + operator is used to add them. The result is stored in the variable sum.
  3. Displaying the output:
    The print() function is used to display the result. We use an f-string to format the output in a user-friendly way, showing both the input numbers and their sum in the output.

Python

Related Articles