Simple Python Program to add Two numbers

Write a Simple Python Program to add two numbers and floating-point values using the Arithmetic Operators with an example.

Simple Python Program to add Two numbers

This example allows the user to enter two values of string type. Next, this program will add those two numbers and assign the total to the variable sum.

number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")

# Using arithmetic + Operator
sum = float(number1) + float(number2)
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))

Adding two numbers output

 Please Enter the First Number: 22
 Please Enter the second number: 44
The sum of 22 and 44 is 66.0

In this example, the following statements ask the user to enter two integer numbers and store the user entered values in variables number 1 and number 2

number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")

Next line, we used Arithmetic Operators ‘+’ to add number1 and number2 and then assigned that total to the sum.

From the below statement, you can observe that we used float type cast to convert the user input values to float.

It is because by default user entered values will be of string type. And if we use the + operator in between two string values, it will concat those two numbers instead of adding them.

sum = float(number1) + float(number2)

The Following Python print statement will print the sum variable as output (22 + 44 = 66).

print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))

This program to add two numbers worked well while adding two positive integers. How about adding positive and negative integers? Let us see

Simple Python Program to add Two Numbers 2

Example 2

It worked fine with negative numbers too! An alternative way of writing the above python add two numbers program is:

number1 = float(input(" Please Enter the First : "))
number2 = float(input(" Please Enter the second : "))

# Using arithmetic + Operator 
sum = number1 + number2
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
 Please Enter the First : 25
 Please Enter the second : 91
The sum of 25.0 and 91.0 is 116.0

NOTE: Above simple program will restrict the user, Not to enter string values as input

Comments are closed.