Python Function Arguments | Args, Kwargs, Lambda

Python function arguments are variables that get passed during the function call.  Sometimes, the argument can have a default value. This is useful if no argument value is passed during the call.

This python function has a default value.

def shout_echo(word1, echo=1):
echo_word = word1 * echo
shout_word = echo_word + ‘!!!’
return shout_word

The function concatenates copies of a word and three
exclamation marks. It can be called with or without a value for echo. If no value for echo is passed, it assumes the default value of 1.

no_echo = shout_echo(‘Hey’)
with_echo = shout_echo(‘Hey’,5)

Functions can also have an unknown number of arguments.

def gibberish(*args):
hodgepodge = ”
for word in args:
hodgepodge += word
return hodgepodge

And it works, whether there are one or many arguments.

one_word = gibberish(‘luke’)
many_words = gibberish(“luke”, “leia”, “han”, “obi”, “darth”)

This same concept can apply to iterate through key-value pairs.

def report_status(**kwargs):
for key, value in kwargs.items():
print(key + “: ” + value)

Call the function with as many key-value pairs desired.

report_status(name=”luke”, affiliation=”jedi”, status=”missing”)

Finally, there are lambda functions. These are useful for writing anonymous functions on the fly. They are commonly used in the context of the map function.

spells = [“protego”, “accio”, “expecto patronum”, “legilimens”] shout_spells = map(lambda item: item + ‘!!!’, spells)
shout_spells_list = list(shout_spells)

Leave a Reply

Your email address will not be published. Required fields are marked *