Functions
Functions are defined with the def
keyword. They can take any number of named arguments, which can be given a default value with an =
. Functions also receive an optional *args
, or postiional arguments, and **kwargs
, or key word arguments.
Functions in python are first-class objects, meaning they can be returned from other functions or passed as arguments into other functions.
python
def hello(name="David"):
return "Hello " + name
def options_args(arg1, *args):
print("First argument :", arg1)
for arg in args:
print("Next argument through *args :", arg)
options_args('Hello', 'Welcome', 'to', 'my', 'docs!')
def optional_kwargs(arg1, **kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
optional_kwargs("Hi", first='Hello', mid='world', last='!')
# Functions can also be returned
def cool():
def super_cool():
return "I am very cool"
return super_cool
# or passed as an argument
def other(some_other_func):
some_other_func()