python functions
built-in & create your own
Quick Facts
When a function does not return results, it is an indication that it was a mutating operation
an exception is the next() function that returns results but mutates the object
Pressing TAB will show a dropdown of options to complete the function
Indentation is important when defining a function because it identifies the scope of the code
If there are multiple functions/calculations, Python will show results for just the last one. To view each result, use the print() function
Functions can take multiple inputs, separated by commas; e.g. function(x, y)
Functional is when a function takes another function as an input; e.g. apply() method for dataframes
Method chaining is applying multiple methods which are functions that belong to a class; e.g. string.lower().split()
Function factories (also called higher order functions) are essentially nested-functions where a function returns a function as output
When in doubt about the number of arguments to pass through a function, we can use *args or **kwargs
Underscore _ can be used as placeholders for values
Use “pass” as a placeholder for functions; e.g. def function(x): pass
In-place vs. Not In-Place
In-place mutates the original object. Check docstring (shift + tab) of a function to double-check if the default inplace is set to True or False
Does not need extra space and produces an output with the same memory that contains the data. (A small constant extra space used for variables is allowed.)
Deals with the idea that the original object doesn’t change, whether a function modifies the original object or simply returns a copy of the object.
Think: do you need the original object? If no, use a mutating method like list.sort(). If yes, use a non-mutating function like sorted() and assign to a new variable.
Lambda vs. Def functions
Def can hold multiple expressions while lambda is a uni-expression function.
Def generates a function and designates a name to call (or execute) it later. Lambda forms a function object and returns it.
Def can have a return statement. Lambda can’t have return statements.
Lambda can be used inside an object, like list or dictionary.
Creating Functions
def - definition, you’re defining the function
function name - name of function follows right after ‘def’; make sure not to use reserved keywords
(x) - parenthesis indicates input of parameter(s) or argument(s); these can be left blank, have one variable, multiple variables, or use *args to allow an arbitrary number of inputs
: - important to end the first line with a colon; it tells Python that all the lines below the colon belong in the function
indentation - when you press enter after the colon, it should automatically indent; if not, make sure to press TAB (or 4 spaces) and follow indentation guidelines
return - end function with ‘return’ to display results; anything written after the return statement will not be within the scope of the function anymore
Lambda is an anonymous function; this is used for quick, one-time use operations
the syntax is lambda <argument(s)> : <expression>
it can take any number of arguments, but can only have one expression
lambda can only take expressions and not statements
examples:
simple — lambda x, y : x + y
follow immediately with the input — lambda age: print(f’I am {age} years old.’)(30)
use in conjunction with .apply() on a pandas dataframe — df[‘col’].apply(lambda x: ‘yes’ if x = 1 else ‘no’)
anti-pattern is bad practice when you assign a lambda function into a variable because it defeats the purpose of lambda
Different ways to use .apply() method as a functional with lambda and function
Try/Except statements are a way of creating custom error messages
the syntax is
try:
<indent><function>
except <error type optional>:
<indent><custom error>if you leave the error type blank, this code will catch all types of exceptions (or errors)
or you can catch multiple exceptions by separating with commas; e.g. except(ValueError, ZeroDivisionError):
examples of errors include: ZeroDivisionError (number is divided by zero), ValueError (function receives the right type but inappropriate value), TypeError (function applied to wrong object type), IndentationError (incorrect indentation), SyntaxError (incorrect formula), view more here
Raise statement is another way of customizing errors; this is used when the code works fine within Python but doesn’t work within the context of the function.
the syntax is raise <error type><message>
can use in conjunction with if/else statements
Conditional Statements
‘If statement’ is a structure that can help Python make decisions based on the input and conditions
‘If statement’ is one type of control flow tool in Python
The condition component of ‘if statements’ are tested for True (also known as Truth Value Testing)
‘If statement’ do not require parentheses and ends with a colon; e.g., if <condition>:
Indentation is important to identify the scope of the conditional statement
The comparison must be of the same data type; e.g., cannot compare a string with an integer
You can use comparison operators (e.g., ==, >, <, <=, >=, !=) and Boolean operators( AND, OR, NOT) to set conditions
Different ways to write ‘if statements’:
‘If statement’ - has one condition and performs one action
‘If-else statement’ - has one condition with two possible actions
‘If-elif-else statement’ - has more than one condition with multiple possible actions
Nested ‘if-else’ statement - has more than one condition in a nested structure with multiple actions
Similar to ‘if-else statements’, the try-except statement keeps the program running and not terminate it mid-way; e.g. trying to open a file where file name does not exist
Recursive Functions
Recursive function is a function defined in terms of itself by self-referencing its expressions; the function will continue to call itself and repeat its behavior until some condition is met to return a result
Built In Functions
Magic method - or “dunder method”; magic methods are called internally from a class on a certain action in the back-end (not by user)
these methods start and end with two underscores; e.g., __add__()
you can see all the magic methods under a certain class by using the dir() function; e.g. dir(int)
these methods happen in the back-end when we use predefined operators in Python
example: when we want to convert ‘10’ into a string, we use the built-in function str(10); in the backend, Python is running the method int.__str__(10)
Popular Built-In Functions: