Python Program to Add Two Numbers

python-program-to-add-two-numbers

In this Python code example, we will discuss a simple Python program to add two numbers. For adding the two given numbers, we have to use the + operator. Also, we need to make use of the print() function to display the result in the console.

Program 1

num1 = # Declare variable num1 and assign it a value of 5
num2 = 10  # Declare variable num2 and assign it a value of 10

# Adding num1 and num2 using + operator and storing the value in variable sum
sum = num1 + num2

# Output the value of sum
print(f"The sum of {num1} and {num2} is {sum}.")

Output:

The sum of 5 and 10 is 15.

Program 2

In this program, instead of using hardcoded values, we will use the Python input() function to let a user declare the two values that are to be added. Also, note that we will declare the input values as integers by using the int() function. In general, the input values are of string type by default, so we need to convert them to integers using the int() function.

num1 = int(input("Enter Value of 1st Number: "))  # Prompt user to provide 1st Number

num2 = int(input("Enter Value of 2nd Number: "))  # Prompt user to provide 2nd Number

# Adding num1 and num2 using + operator and storing the value in variable sum
sum = num1 + num2

# Output the value of sum
print(f"The sum of {num1} and {num2} is {sum}")

Output:

Enter Value of 1st Number: 5
Enter Value of 2nd Number: 10
The sum of 5 and 5 is 10.

Program 3

It is possible to add float numbers as well. You simply need to convert the input string values into float values by using the float() function.

num1 = float(input("Enter Value of 1st Number: "))  # Prompt user to provide 1st Number

num2 = float(input("Enter Value of 2nd Number: "))  # Prompt user to provide 2nd Number

# Adding num1 and num2 using + operator and storing the value in variable sum
sum = num1 + num2

# Output the value of sum
print(f"The sum of {num1} and {num2} is {sum}.")

Output:

Enter Value of 1st Number: 5.5
Enter Value of 2nd Number: 6.5
The sum of 5.5 and 6.5 is 12.0.

Takeaway

In Python, adding two numbers that can be of integer or float types is quite simple. We have discussed three different Python programs to add two numbers above to help you understand better. We discussed how to add hardcoded values as well as values provided by the user.

Share Your Thoughts, Queries and Suggestions!