Add Two Integers
The most basic Python program to add two integer numbers stored in variables num_1
and num_2
is the expression num_1 + num_2
using the addition operator.
The following code shows how to add two numbers 20 and 22 and print the result 42 to the shell:
# Python Program to Add Two Integers num_1 = 20 num_2 = 22 result = num_1 + num_2 print(num_1, '+', num_2, '=', result) # 42
Add Two Integers with User Input
Use the following four steps to create a simple addition program in Python taking the user’s input and adding together the provided numbers.
- Get the user input as a string using the built-in
input()
function, and store the result in variablesnum_1
andnum_2
. - Convert the string user inputs to an integer using the
int()
built-in method. - Add together the numerical values using the addition operator
num_1 + num_2
. - Print the result to the Python shell.
Here are those four steps in Python code:
# Python addition program with user input # 1. Get string user inputs representing integers num_1 = input('First number: ') num_2 = input('Second number: ') # 2. Converting strings to ints num_1 = int(num_1) num_2 = int(num_2) # 3. Adding numbers result = num_1 + num_2 # 4. Display the result print(num_1, '+', num_2, '=', result)
Here’s an example code execution where I put in integers 40 and 2 and calculated the sum of both using the addition operator:
First number: 40 Second number: 2 40 + 2 = 42
Add Two Floats with User Input
Use the following four steps to create a simple addition program in Python taking the user’s input and adding together the provided numbers.
- Get the user input as a string using the built-in
input()
function, and store the result in variablesnum_1
andnum_2
. - Convert the string user inputs to a floating point number using the
float()
built-in method. - Add together the numerical values using the addition operator
num_1 + num_2
. - Print the result to the Python shell.
Here are those four steps in Python code:
# Python addition program with user input # 1. Get string user inputs representing floats num_1 = input('First number: ') num_2 = input('Second number: ') # 2. Converting strings to floats num_1 = float(num_1) num_2 = float(num_2) # 3. Adding floats result = num_1 + num_2 # 4. Display the result print(num_1, '+', num_2, '=', result)
Here’s an example code execution where I put in floats 40.2 and 1.8 and calculated the sum of both using the addition operator:
First number: 40.2 Second number: 1.8 40.2 + 1.8 = 42.0
Video Addition Operator Deep Dive
You can learn more about the Python addition operator in my detailed blog tutorial: