Functions
Functions. We are all know them. We are love them. But what are they really. Functions are blocks of statements that return something specific. Let break it down:
def function(input):
something = some_statements(input)
return something
You can all a function like so:
function()
Wow, that was easy. We can also add some protections like type hinting. This will allow us to "hint" what type the input should be and what type the output of the function should be:
def function(input: data_type) -> return_type:
something = some_statements(input)
return something
Variable Number of Arguments with *arg
and **kwargs
What if you had an indeterminate number of arguments that could be passed to a function. Let's look at an example:
def print_stuff(*arg):
return(arg)
print_stuff("test", "this")
If we run this function, it will return a list containing whatever arguments were passed in *arg
which in this case is ("test", "this")
.
We could run through each item in our list like so:
def print_stuff(*arg):
for i in arg:
print(i)
print_stuff("test", "this")
Now when we run this function, it will first print "test"
and then print "this"
.
However, if you add a return statement, it will just return the first value in the list:
def print_stuff(*arg):
for i in arg:
return(i)
print_stuff("test", "this")
We can use **kwargs
when we are passing variable number of names arguments to a function, which will look a bit like passing items from a dictionary to a function.
def print_stuff(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
print_stuff(first='Geeks', mid='for', last='Geeks')