Write a Simple Python Program with example. In order to show, we are going to add two numbers using Arithmetic Operators
Simple Python Program to add Two numbers
This simple Python program to add two numbers allows the user to enter two values. Next, it will add those two numbers and assign the total to variable sum.
# Simple Python program to Add Two Numbers number1 = input(" Please Enter the First Number: ") number2 = input(" Please Enter the second number: ") # Using arithmetic + Operator to add two numbers sum = float(number1) + float(number2) print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
In this simple python program to add two numbers example, the following statements ask the user to enter two integer numbers and stores 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 Python Arithmetic Operators ‘+’ to add number1 and number2 and then assigned that total to sum.
From the below statement you can observe that, we used float type cast to convert the user input values to float. This is because, by default user entered values will be of string type and if we use the + operator in between two string values python will concat those two values instead of adding them
sum = float(number1) + float(number2)
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 python program to add two numbers worked well while adding two positive integers, How about adding positive and negative integer? Let us see
Sample Python Program to add Two numbers Example 2
It worked fine with negative numbers too!. Alternative way of writing the above python add two numbers program is:
# Simple Python program to Add Two Numbers number1 = float(input(" Please Enter the First Number: ")) number2 = float(input(" Please Enter the second number: ")) # Using arithmetic + Operator to add two numbers sum = number1 + number2 print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
NOTE: Above simple program will restrict the user, Not to enter string values as input