-
Notifications
You must be signed in to change notification settings - Fork 0
6. Functions
In Python, like most programming languages we can encapsulate logic inside a "function" in order to reuse it in a generic way. Functions are defined using the def word to imply a function, the function's name obeys Python's variable naming conventions. After the name comes a list of arguments (possibly 0) inside ( , ). The arguments' names must also obeys Python's variable naming conventions. Arguments can also have default values denoted by initializing the argument's variable name with a value such as arg_name='noName'. A : marks the end of the definition line. Inside the function, Python's interpreter expects a new code block, i.e., the code inside the the function is indented, similarly to inside a loop or a condition. For example:
def my_func(some_string=''):
print(len(some_string))
return some_string + '!'So, my_func will print a length of a string and will return a new string comprised out of the argument string and "!" added to its suffix. The string defaults to the empty string.
This function can be used:
my_func() # prints the empty string and returns '!'
my_func('') # also prints the empty string and returns '!'
my_func('ABC') # prints 'ABC' and returns 'ABC!'A function's arguments can also be arbitrary lists or dict's.
More about functions. A list of Python's built-in functions. More about arguments.
When using functions, there's the possibility of making recursive calls. More about that here.
When using functions it's important to understand scoping and how it's used in Python. A scope means the areas of the code where variable (including function) names are recognized (and as what). Here are programiz and real python's explanations.
Anonymous/Lambda Function is a way to write in-line functions. By their nature, those have to be simple. It's usin the lambda keyword:
var_name = lambda arg_name_inside: arg_name_inside * 2
var_name(2) # returns 2*2 = 4More on lambda
Note you can write functions (lambda or regular) inside other functions. This where things start to get freaky with the scopes. More on nested functions.
We won't discuses this in length here but - Classes could also have functions - they're called "methods". They could also have attributes which are infect lambdas.
- Looking back on all the exercises so far - where would writing a function improve your code? Improve it then...