Python Program to Add two numbers2 min read

To add numbers in python, firstly we have taken these two numbers from the user using the input() function. We have to typecast the returned value from the input function to int as the return value from input() function is a string.

And then add these two numbers and store it in third variable sum. After that print the sum on the output window.

Code to add two numbers in python

Now if the numbers containing a decimal then how to add these numbers?

Add two numbers containing decimal

Almost all the code is same as above except some changes made to accept the numbers containing decimal and also show the output in formatted form.

So, to accept the numbers containing decimal we typecast the input() function to float. Hence, we will be able to get the numbers containing the decimal. Now to output the sum in a formatted form we will use format() in-build function of python.

format() function accepts two parameters. The first parameter is the number itself which we want to format and the second parameter is format specifier which tells how we want to format the number passed as the first argument.

Code to add two numbers containing decimal in python

Now let see what above format specifier means.
< – It is used to align the number to the right.
20 – It specifies the width of the number(including the decimal).
.4 – It tells the precision of the number, in this case, it is 4.
f – It specifies that the number is a float.

Now, try to make a program to add three numbers.

Leave a Comment