2

Tech Blog

×

Warning

JUser: :_load: Unable to load user with ID: 94
Thursday, 09 June 2022 12:02

How to Use Variable and Keyword Arguments in Python

Written by
Rate this item
(0 votes)

How to Use Variable and Keyword Arguments in Python

Make your functions more flexible and easier to use with these variations on standard arguments.

There are three types of arguments that a Python function can accept: standard, variable (*args), and keyword (**kwargs). Standard arguments are the simplest but have limited functionality. On the other hand, *args and **kwargs enable you to make your functions more flexible, by accepting a variable number of inputs.

The type of argument-passing you choose depends on the nature of your function and your own preferred programming style.

To understand how the two variable arguments in Python functions work, it's essential to understand why they exist in the first place. A simple function declares a fixed number of anonymous arguments like so:

def addnum(a, b, c):
return a + b + c

This function works fine, but there's room for improvement. The biggest issue is that it only handles two arguments, so it can only add up two number. What if you want to add two or four numbers? This function will not allow you to do so. Passing more or fewer arguments than the function accepts will lead to a TypeError.

Of course, you could create more functions to accept different numbers of arguments. But that's inconvenient and won't scale well at all. You'll also need to create a new function every time you want to handle a new number of inputs.

That's where variable arguments and keyword arguments come in. Using *args and **kwargs, you can define flexible functions that can take a variable number of inputs.

 

What Is *args in Python?

The main idea behind *args in Python is to allow you to pass a variable number of inputs to your function. This comes in handy in various applications. For instance, think of a calculator program where you want to give the user ability to add two or more numbers and return the sum.

Note that args is just a variable name; it's the * that's important. You can use any valid name for your variable argument, as long as you include the *.

 

How to Use *args

You can modify the addnum function to take a variable number of inputs as follows:

def addnum(*args):
total = 0

for num in args:
total = total + num

return total

The code snippet above uses a for loop to iterate through the supplied inputs.

You can then call the addnum function with variable arguments and it will work without throwing an error:

print(addnum(10, 1, 12, 12, 4, 54, 5)) ## returns 98
print(addnum(14, 54, 5)) # returns 73
print(addnum(10, 5)) # returns 15
 

What Is **kwargs in Python?

While both *args and **kwargs allow us to pass a variable number of inputs to functions, the latter is specific to keyword arguments. In case you don't know, keyword arguments are just fancy names for arguments with a name.

Another unique thing about **kwargs is that Python represents the value as a dictionary.

 

How to Use **kwargs

Like *args, the double-asterisk is the important bit; you can use any word as a parameter name. Here's an example of how to use **kwargs in Python:

def weekly_attendance(**weekdays):
total_attendees = 0

for attendees in weekdays.values():
total_attendees = total_attendees + attendees

return total_attendees

print(weekly_attendance(monday = 265, tuesday = 698, wednesday = 365, thursday = 463, friday = 234)) # returns 2025
print(weekly_attendance(monday = 265, friday = 234)) # returns 499
print(weekly_attendance(wednesday = 365, thursday = 463, friday = 234)) # returns 1062

The code snippet above also uses a for loop, but this time with Python's built-in values() method. That method returns a view object of all the values in the dictionary. The values() method allows you to loop through a Python dictionary without hassle.

Use Variable Arguments to Make Your Python Functions Flexible

Function arguments are handy, but some functions can benefit from accepting a variable number of arguments. Named keyword arguments can make your code more readable and easier to use. You should embrace Python's *args and **kwargs arguments. They are pretty simple to use, and with them, you can make your functions and programs more flexible.

By following the steps and code snippets above, we hope that you can now use variable keyword and non-keyword arguments for your functions.

Source: MUO

Read 518 times Last modified on Thursday, 23 June 2022 12:17

IT Solutions and Support

We are an Information Technology Company driven by service excellence, simplicity, effectiveness, efficiency and timeliness.

We take care of the modern-day tool of business (Information Technology) to allow our clients to focus on their business goals and objectives.

Get In Touch

5 Babajide Close, Off Association Avenue, Ikotun, Lagos

+234 803 3233 193

+234 814 5636 831

info@tishritechnologies.com

https://www.tishritechnologies.com