Skip to content
Related Articles
Open in App
Not now

Related Articles

Python program to add two numbers

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 13 Mar, 2023
Improve Article
Save Article

Given two numbers num1 and num2. The task is to write a Python program to find the addition of these two numbers. 

Examples:

Input: num1 = 5, num2 = 3
Output: 8

Input: num1 = 13, num2 = 6
Output: 19

In the below program to add two numbers, the user is first asked to enter two numbers and the input is scanned using the input() function and stored in the variables number1 and number2. Then, the variables number1 and number2 are added using the arithmetic operator + and the result is stored in the variable sum. Below is the Python program to add two numbers: 

Example 1: 

Python3




# Python3 program to add two numbers
  
num1 = 15
num2 = 12
  
# Adding two nos
sum = num1 + num2
  
# printing values
print("Sum of {0} and {1} is {2}" .format(num1, num2, sum))

Output:

Sum of 15 and 12 is 27

Example 2: Adding two number provided by user input 

Python3




# Python3 program to add two numbers
  
number1 = input("First number: ")
number2 = input("\nSecond number: ")
  
# Adding two numbers
# User might also enter float numbers
sum = float(number1) + float(number2)
  
# Display the sum
# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1, number2, sum))

Output:

First number: 13.5 Second number: 1.54
The sum of 13.5 and 1.54 is 15.04

Example 3:

Python3




# Python3 program to add two numbers
  
# Driver Code
if __name__ == "__main__" :
    
  num1 = 15
  num2 = 12
    
  # Adding two numbers
  sum_twoNum = lambda num1, num2 : num1 + num2
    
  # printing values
  print("Sum of {0} and {1} is {2};" .format(num1, num2, sum_twoNum(num1, num2)))

Output:

Sum of 15 and 12 is 27;

Example 4: Adding two numbers using by defining add function and return the result

Python3




#To define a function that take two integers and return the sum of those two numbers
def add(a,b):
  return a+b
  
#initializing the variables
num1 = 10
num2 = 5
  
#function calling and store the result into sum_of_twonumbers
sum_of_twonumbers = add(num1,num2)
  
#To print the result
print("Sum of {0} and {1} is {2};" .format(num1, num2, sum_of_twonumbers))

Output

Sum of 10 and 5 is 15;

Time Complexity : O(1)

Space Complexity : O(1) 

Example 5 : Using operator.add() method

Approach

  1. Initialize two variables num1,num2
  2. Find sum using operator.add() by passing num1,num2 as arguments and assign to su
  3.  Display num1,num2 and su

Python3




# Python3 program to add two numbers
  
num1 = 15
num2 = 12
  
# Adding two nos
import operator
su = operator.add(num1,num2)
  
# printing values
print("Sum of {0} and {1} is {2}" .format(num1, num2, su))

Output

Sum of 15 and 12 is 27

Time Complexity : O(1)

Auxiliary Space : O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!