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
1 2 3 4 5 6 7 8 9 10 11 12 | # taking and storing first number in num1 variable num1 = int(input("Enter first number: ")) # taking and storing second number in num2 variable num2 = int(input("Enter second number: ")) # adding the two numbers and storing it in sum variable sum = num1 + num2 # printing the sum print("Sum of two numbers is ",sum) |
1 2 3 4 5 | Enter first number: 45 Enter second number: 56 Sum of two numbers is 101 |
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
1 2 3 4 5 6 7 8 9 10 11 12 | # taking and storing first float number in num1 variable num1 = float(input("Enter first number: ")) # taking and storing second float number in num2 variable num2 = float(input("Enter second number: ")) # adding the two numbers and storing it in sum variable sum = num1 + num2 # printing the sum print("Sum of two numbers is",format(sum,"<20.4f")) |
1 2 3 4 5 | Enter first number: 25.368 Enter second number: 152.5684 Sum of two numbers is 177.9364 |
< – 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.