In this Python tutorial, I will explain how to add two numbers in Python using the function. We will see many different ways to add numbers within a function in Python with some demonstrative examples.
A function in Python is a block of organized and reusable code that is used to perform a single related action. The usage of functions makes our code more modular and easier to manage.
Python provides built-in functions like print(), but we can also create our functions. These functions are called user-defined functions. We can define functions to provide the required functionality. Here’s a simple example:
def say_hello():
print("Hello!")
say_hello()
And we can call it like say_hello() anywhere in the Python program.
Hello!
In our context, we will explore the “addition function” in Python, which is essentially a function that allows the addition of two numbers.
Adding two numbers in Python using the function
There are five different ways for the addition of two numbers in Python using function.
- Basic Function
- Using
sum()
with Generators - Using *args for Variable Number of Arguments
- Using Lambda Function
- Recursive Function
Let’s see them one by one with examples:
Method-1: Basic Function to Add Two Numbers in Python using the function
A straightforward Python function that accepts two parameters and returns their sum. Ideal for scenarios where only two numbers need to be added.
Example-1: For instance, Imagine we’re shopping in New York City and want to buy two items: a Statue of Liberty souvenir for $10 and a New York Yankees cap for $25. So, let’s try add these values in Python.
def add(a, b):
return a + b
print("Total cost:", add(10, 25))
Here, we’ve created a simple Python function add
that accepts two arguments and returns their sum. This is straightforward addition.
The output is:
Total cost: 35
This way we can simply add two numbers in Python using def function.
We can also take the input from the user and add two numbers in this simplest way of addition in Python.
Example-2: Take the above scenario, Now the shopkeeper will manually add the price for each by himself in Python.
def add(a, b):
return a + b
price1 = float(input("Enter the price for 1st product: "))
price2 = float(input("Enter the price for 2nd product: "))
print("Total price to pay:", add(price1, price2))
The output is:
Enter the price for 1st product: 10
Enter the price for 2nd product: 25
Total price to pay: 35.0
Note: In real-world scenarios, we may want to ensure that the user should provide valid numbers. This can be done using exception handling: The try and except block in Python.
This way we can even add two user input numbers Python using Function.
Method-2: Using Python’s Built-in sum()
with Generators to add function in Python
The sum()
function in Python is a built-in function that takes an iterable (e.g., a list or tuple) and returns the sum of its elements. If a second argument is provided, it is added to the sum of the elements.
This technique involves using a generator expression within the sum() Python function. It’s beneficial for summing a range of numbers without creating a separate list in memory.
For example, We’re saving up every month for a trip to Disneyland. We want to find out how much we’ve saved from January (1
) to April (4
) through Python coding.
def add_range(start, end):
return sum(i for i in range(start, end+1))
print("Total savings:", add_range(1, 4))
The output is:
Total savings: 10
This uses a generator inside the sum()
function in Python to add up numbers in a range.
Method-3: Using *args for the sum of variable number of arguments in Python
Utilizes *args
to allow the function to accept a variable number of arguments. The built-in sum() function in Python then, totals all these arguments. Best for summing an unknown number of elements.
For instance, We’re hosting a July 4th BBQ and are buying several items with varying costs. We want an easy way to find the total cost through some code in Python.
def add(*args):
return sum(args)
print("Total BBQ cost:", add(30, 35))
The output is:
Total BBQ cost: 65
The *args
in Python allows us to pass multiple arguments to the function and the sum() function then totals them up.
Method-4: Python lambda function to add two numbers.
A lambda Python function is a concise, anonymous function defined using the lambda
keyword. This method quickly defines a function to add two numbers without formally naming it. Useful for short-lived functions.
Example-1: For instance, We’re at a Texas state fair and quickly want to add the price of a rodeo ticket and a Ferris wheel ride in Python.
add = lambda a, b: a + b
print("Total cost:", add(15, 5))
The output is:
Total cost: 20
A lambda Python function is a small anonymous function. It’s a quick, concise way to declare small functions.
Example-2: Adding user input numbers using the lambda function in Python. In the above scenario, this time, we will provide the price of the fairs when asked only.
add = lambda a, b: a + b
ride1 = float(input("Enter the cost of 1st ride: "))
ride2 = float(input("Enter the cost of 2nd ride: "))
print("Total cost is:", add(ride1, ride2))
The Output is:
Enter the cost of 1st ride: 15
Enter the cost of 2nd ride: 5
Total cost is: 20.0
This way we can take user inputs from the user and add them with a lambda function in Python.
Method-5: Recursive function to add two numbers in Python
A recursive Python function calls itself with a modified argument until a base condition is met. In the context of addition, it keeps adding numbers detrimentally until reaching zero.
During Our visit to Hollywood, we bought several movie memorabilia items. We wish to find out our total expenditure in Python.
def recursive_add(expense):
if not expense:
return 0
return expense[0] + recursive_add(expense[1:])
expense_input = input("Enter numbers separated by spaces: ")
expense_list = [float(expenditure) for expenditure in expense_input.split()]
print("Total expenditure is:", recursive_add(expense_list))
The output is:
Enter numbers separated by spaces: 45 21
Total expenditure is: 66.0
This way we can ask users to give(user input) there all their input at one time and we can add numbers in Python using the recursive function.
Conclusion
In this tutorial, we have seen how to add two numbers in Python using the function using 5 different ways like a basic function, sum()
with generators, *args, lambda function, or recursive function to add numbers with some demonstrative examples. Each Python method provides different tools for various scenarios. Understanding which one to use and when helps streamline our coding process
You may also like to read:
- How to add two numbers in Python [6 different methods]
- How to add zeros before a number in Python
- How to Add Numbers in a List in Python Without Sum
- Add two numbers without using + operator in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.