Python Functions

Python functions:

def say_hello(name):

print(“Hello there, ” + name + “!”)

def main():

say_hello(“Alan”)

Python *args and **kwargs (arguments and key word arguments):

*args allows you to pass an indeterminate number of arguments to a function. For example:

cart_item = “broccoli beef chicken cereal milk oj coffee”.split()

other_thing = “asdfg”

some_other_arg = “blah”

def example_args(*args):

for thing in args:

print(thing)

example_args(cart_item[0], other_thing, cart_item[1], some_other_arg, cart_item[3])

print(“===========”)

example_args(cart_item[0], other_thing)

In the above case, you can invoke the function with varying amounts of arguments. These are passed as a list.

**kwargs is like *args, but for key-value pairs, such as the following example:

def example_kwargs(**kwargs):

for key,value in kwargs.items():

print(str(key) + “: ” + str(value))

example_kwargs(major = “computer science”, something = “whatever”)

example_kwargs(key1 = “value1”, key2 = “value2”, key3 = “value3”,

key4 = “value4”, key5 = “value5”, key6 = “value6”)

Again, notice how a function with **kwargs can accept any number of key-value pairs. Also, for a dictionary, you can use the .items() method to get all the items in it, which consist of keys and values.

Python lambda expressions:

Recall that a lambda expression is also called an anonymous function, as it has no name.

Below is an example lambda expression in python that calculates the area of a rectangle:

def area(x):

return lambda y: y * x

baseheight = area(5)

rectangle = baseheight(10)

print(rectangle)

It might be a little confusing, but the benefit is that you can have functions within other functions. If you don’t like lambdas, you can always just use regular functions instead. Lambda expressions are by no means necessary to code. But they can be convenient in some cases.

← Previous | Next →

Python Topic List

Main Topic List

Leave a Reply

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