Python program to add two numbers


In this example, you will learn about the Python program to add two numbers.

For a better understanding of the example, you need to have a proper understanding of the following topic:

Python program to add two numbers

#simple python program to add two numbers
#first assign values to variables
var1 = 2.3
var2 = 4.3

#now add those variables
sum1 = int(var1) + int(var2)
sum2 = float(var1) + float(var2)

#print sum to output console
print('The sum of integer part is ',sum1)
#another way to print
print('The sum of {0} and {1} is {2}'.format(var1, var2, sum1))

print('The sum of floating numbers is ',sum2)
print('The sum of {0} and {1} is {2}'.format(var1, var2, sum2))

Output

The sum of integer part is 6
The sum of 2.3 and 4.3 is 6

The sum of floating numbers is 6.6
The sum of 2.3 and 4.3 is 6.6

Explanation of the program

First we assigned values to two different variables var1 and var2.

Next line of codes are:

sum1 = int(var1) + int(var2)
sum2 = float(var1) + float(var2)

So, what actually are we doing here?

Here we are simply typecasting to convert input values to integers and floating point numbers. So the variable sum1 will carry the sum of input numbers as integers i,.e 2 and 4. And sum2 will carry the sum of input numbers as floating point numbers i.e 2.3 and 4.3.

Next line of codes is the demonstration of how those sums can be presented in the output console in different ways.

Python program to add two numbers: Ask input from users

#ask user to enter numbers
var1= input('Enter first number:')
var2= input('Enter second number:')

#add the entered numbers
sum = int(var1) + int(var2)

#print the sum to output console
print('The sum is ',sum)

Output

Enter first number: 1
Enter second number: 2
The sum is 3

Explanation of the program

This is also the same program that will add two numbers, but it will ask those two numbers from the user.

Note: typecasting is essential when we ask the user to enter values because by default the values entered by the user are taken as string types. And if not typecasted to convert into integers, the ‘+’ operator will simply concatenate the input.

For example:

Python program to add two numbers

As you can see in the above example, if not typecasted as an integer, Python will simply take input as a string and concatenate them.