print(“Hello there, ” + name + “!”)
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”
for thing in args:
example_args(cart_item, other_thing, cart_item, some_other_arg, cart_item)
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:
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:
return lambda y: y * x
baseheight = area(5)
rectangle = baseheight(10)
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.