How to Add Two Numbers in Python

Adding two numbers is one of the most basic operations in programming and Python provides simple and efficient ways to perform this task. This article will cover different methods to add two numbers including basic arithmetic operations, using functions and handling user input.

Introduction

Adding two numbers can be done using the + operator in Python. This operation can be performed on various types of numbers including integers, floats and even complex numbers. In this article, we will explore multiple approaches to adding two numbers and provide examples for each method.

Basic Arithmetic Operation

The most straightforward way to add two numbers in Python is by using the + operator.

Example

# Adding two integers
num1 = 10 num2 = 20 sum = num1 + num2 print("Sum of", num1, "and", num2, "is", sum) # Adding two floating-point numbers num1 = 10.5 num2 = 20.3 sum = num1 + num2 print("Sum of", num1, "and", num2, "is", sum)

Output

Sum of 10 and 20 is 30
Sum of 10.5 and 20.3 is 30.8

Using Functions

You can create a function to add two numbers. This is useful for code reusability and organization, especially when you need to perform the addition operation multiple times.

Example


def add_numbers(a, b):
return a + b # Using the function to add two integers result = add_numbers(10, 20) print("Sum is", result) # Using the function to add two floating-point numbers result = add_numbers(10.5, 20.3) print("Sum is", result)

Output

Sum is 30
Sum is 30.8

Handling User Input

In many applications, you may need to take input from the user and add the numbers provided. You can use the input() function to get user input and then convert it to the appropriate number type before performing the addition.

Example

# Taking input from the user
num1 = input("Enter first number: ") num2 = input("Enter second number: ") # Converting input to float num1 = float(num1) num2 = float(num2) # Adding the numbers sum = num1 + num2 print("Sum of", num1, "and", num2, "is", sum)

Output

Enter first number: 12.5
Enter second number: 7.3 Sum of 12.5 and 7.3 is 19.8

Adding Complex Numbers

Python also supports complex numbers and you can add them using the + operator.

Example

# Adding two complex numbers
num1 = complex(2, 3) num2 = complex(1, 4) sum = num1 + num2 print("Sum of", num1, "and", num2, "is", sum)

Output


Sum of (2+3j) and (1+4j) is (3+7j)

Using Lambda Functions

Lambda functions offer a concise way to write small, anonymous functions. You can use a lambda function to add two numbers.

Examplepython

# Using a lambda function to add two numbers add = lambda a, b: a + b # Adding two integers result = add(10, 20) print("Sum is", result) # Adding two floating-point numbers result = add(10.5, 20.3) print("Sum is", result)

Output

Sum is 30 
Sum is 30.8 

Post a Comment

Previous Post Next Post