In this Article, We will see How to add two numbers in Python.
Example:
Input: number1 = 12, number2 = 13 Output: 25 Input: number1 = 10, number2 = 40 Output: 50
Now, let’s see the different ways to code:
Code 1:
# Code - 1 # Given input numbers number_1 = 12 number_2 = 13 # perform addition print(number_1 + number_2)
Output:
25
Code 2:
# Code - 2
# Main Code
if __name__ == "__main__" :
# Given input numbers
number_1 = 12
number_2 = 13
# perform addition
print(number_1 + number_2)
Output:
25
Code 3:
# Code - 3
# Main Code
if __name__ == "__main__" :
# take string input from user
number_1 = input("Enter 1st Number: ")
number_2 = input("Enter 2nd Number: ")
# type casting into integer
number_1 = int(number_1)
number_2 = int(number_2)
# perform addition
print(number_1 + number_2)
Output:
Enter 1st Number: 10 Enter 2nd Number: 40 50
Code 4:
# Code - 4
# Main Code
if __name__ == "__main__" :
# take string input from user
number_1 = input("Enter 1st Number: ")
number_2 = input("Enter 2nd Number: ")
# type casting into integer
# and then perform addition
print(int(number_1) + int(number_2))
Output:
Enter 1st Number: 10 Enter 2nd Number: 40 50
Code 5:
# Code - 5
# Main Code
if __name__ == "__main__" :
# take integer input from user
number_1 = int(input("Enter 1st Number: "))
number_2 = int(input("Enter 2nd Number: "))
# perform addition
print(number_1 + number_2)
Output:
Enter 1st Number: 10 Enter 2nd Number: 40 50
Code 6: By creating user-defined function.
# Code - 6
# Create a user-defined function
# For adding two numbers
def sum_2_numbers(number_1, number_2) :
# return addition of 2 numbers
return number_1 + number_2
# Main Code
if __name__ == "__main__" :
# take integer input from user
number_1 = int(input("Enter 1st Number: "))
number_2 = int(input("Enter 2nd Number: "))
# Function calling
print(sum_2_numbers(number_1, number_2))
Output:
Enter 1st Number: 10 Enter 2nd Number: 40 50
Code 7: By using Lambda function.
# Code - 7
# Create an anonymous/lambda function
# For adding two numbers
sum_2_numbers = lambda number_1, number_2 : number_1 + number_2
# Main Code
if __name__ == "__main__" :
# take integer input from user
number_1 = int(input("Enter 1st Number: "))
number_2 = int(input("Enter 2nd Number: "))
# Function calling
print(sum_2_numbers(number_1, number_2))
Output:
Enter 1st Number: 10 Enter 2nd Number: 40 50