if condition:
my_code()
else:
my_other_code()
for
loops iterate through elements in a collectionfor x in collection:
do_something_with_x()
while
loops run until a condition is no longer truewhile x > 3:
do_something()
A fundamental precept of good programming is Don't Repeat Yourself, often abbreviated DRY. Repetition can happen when you want to do one operation (or a slight variant) several times and simply copy and paste your code to achieve that goal.
Copy-pasting is almost always a red flag that you're violating DRY!
Repetition leads to a few problems:
The best solution to DRY is usually functions.
Functions are code blocks that can be saved. Functions have names, and if they're named well you can easily understand what they're for.
mylist = ['brad', 'ethan']
len(mylist)
2
len
is a function to return the length of a list.
Functions that come with Python tend to have short names since they're used so much.
len
abstracts away a block of code so we don't have to think about how it works.
But what might be inside the len
function?
counter = 0
for item in mylist:
counter = counter + 1
print(counter)
2
The great thing about functions, like len
, is that they allow us to avoid rewriting the underlying logic (like the above for
loop) every time we want to do a common operation.
Functions in other libraries are often named more verbosely -- which can be helpful since it tells us how to use them.
date_string = '2019-01-01'
date_string
'2019-01-01'
import datetime as dt
# Convert the date string into a datetime
dt.datetime.strptime(date_string, "%Y-%m-%d")
datetime.datetime(2019, 1, 1, 0, 0)
datetime's strptime
function converts string into a datetime
object.
The most fundamental property of a function -- both in math and in programming -- is that it transforms inputs into outputs.
For example, absolute value is a function.
The absolute value of x (in math, often written |x|
) is x when x is positive, but (-x) when x is negative.
x | f(x) |
---|---|
1 | 1 |
2 | 2 |
-1 | 1 |
-5 | 5 |
Python has a built-in version of the absolute value function.
abs(1)
1
abs(-5)
5
In the context of functions, inputs are called arguments, and outputs are called return values.
In abs(-5)
, the function argument is -5 and the return value is 5.
You've used plenty of functions that others have written for you, but as your Python projects become more complicated you'll want to begin writing your own functions to follow the DRY principle.
In Python, functions are created using two new keywords, def
(as in def
ine) and return
.
The general structure is:
def myfunction(arguments):
code_block
return return_value
The return
keyword is optional -- your function doesn't have to return a value.
It might do something else, like modify a DataFrame.
But if your function produces some kind of output, return
is the way to express that.
Let's write a function that doubles a number and call that function double
.
def double(number):
doubled_number = number * 2
return doubled_number
We can call our new function the same way we would with any function in Python.
double(3)
6
x = 5
double(x)
10
double
works just the same as abs
-- in Python, there's nothing stopping you from building new functions that work as seamlessly as the built-in functions.
Functions can take multiple arguments. We could write a function to return the product of two numbers.
def multiply(x, y):
product = x * y
return product
multiply(7, 4)
28
Note that the names we use for arguments and return values (here x
, y
, and product
) aren't relevant outside the function.
We say that they exist only within the scope of the function.
The area of a triangle is \begin{equation*} A = \frac{h * b}{2} \end{equation*} where h is the height and b is the length of the base.
Write a function called area
that takes arguments h
and b
and returns the area of a triangle with those dimensions.
Functions unlock a great deal of power in programming. It's often handy to write functions that handle data manipulation workflows that you do regularly.
Take this data:
data
{'001': 'Smith Real Estate, Inc.', '002': 'Johnson Realty', None: 'John Doe Real Estate, LLC'}
Maybe you commonly work with data like this and always:
It's simple to write a function that will do that in a single line for you.
def clean(data):
# Updating keys and values means we should start with a blank dictionary
clean_data = {}
for id, name in data.items():
# Only keep values where the ID is not missing
if id is not None:
# Make the name lowercase
clean_data[id] = name.lower()
return clean_data
clean(data)
{'001': 'smith real estate, inc.', '002': 'johnson realty'}
We can then apply this function to other similarly-structured data.
data2
{'123': 'Berkshire Hathaway', None: 'Howard Hannah', '321': "Southeby's"}
clean(data2)
{'123': 'berkshire hathaway', '321': "southeby's"}
There's no limit to how much complexity or code can be put in a function. In software development, it's not uncommon to find functions with hundreds of lines.
Moving lots of logic into functions can help programmers simplify their code -- rather than look at the function logic each time, they can get an idea of what's happening by just seeing the function name.
How does Python know which argument is which when we pass multiple?
For example
def raise_to_power(a, b):
return a ** b
raise_to_power(2, 3)
8
It's clear that a
was set to 2
and b
to 3
, because we got 8 (23) as our result.
Why didn't the opposite happen? How did Python know that we didn't mean that b
should be 3
and a
should be 2
?
It's because Python respects the order of arguments; it assigns our arguments to variables in the order that they're passed in.
There's another, more explicit, way to tell Python which value goes with which argument: named arguments, also called keyword arguments.
raise_to_power(a=3, b=1)
3
raise_to_power(b=1, a=3)
3
In this format, the syntax argument_name=value
specifies which value goes where; the order no longer is important.
If you mix positional and keyword arguments, all the positional ones must come first -- this allows Python to disambiguate how to match the inputs to arguments.
A handy feature of Python is default argument values -- the ability to set a default for arguments the user may choose not to pass in.
Let's look at an example.
def favorite(number=5):
return 'My favorite number is ' + str(number)
This function takes an input -- your favorite number -- and prints out a sentence indicating that it's your favorite.
favorite(10)
'My favorite number is 10'
favorite(number=8)
'My favorite number is 8'
However, this function also has a default number in case you don't specify one; that's what number=5
means, as one of the arguments.
If we call favorite without specifying an input, it assumes we want number
to be 5.
favorite()
'My favorite number is 5'
This functionality is extremely useful for functions that allow the user to customize certain options -- but don't want the user to have to specify them every time.
A good example is the built-in print
function. We've seen it before, but we usually only specify a single argument: an object.
x = 'some string'
print(x)
However, if you consult the documentation, you discover that print
allows for optional customizations.
We usually pass the first one (named value
), but not the others, like sep
, end
, or flush
.
print?
Docstring: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. Type: builtin_function_or_method
Usually, you don't need to specify things like the separator or end value; there are intelligent defaults, so you only need to worry about them in specific scenarios.
Just as it's best practice to document your code by using comments, it's good form to notate your functions so others (and you) can quickly learn about them -- what they do, what arguments they take, and what value they return.
In Python, this is typically done using a docstring, an optional but very helpful annotation of a function.
def double(x):
'''Multiply x by 2 and return the result.'''
doubled = x * 2
return doubled
Of course, for a function as simple as the above, you could just figure it out from the code. But as functions grow more complex, this documentation becomes more and more useful.
Docstrings are what you've been seeing if you use the function?
syntax.
Python fetches that function's docstring and shows it to you.
double?
Signature: double(x) Docstring: Multiply x by 2 and return the result. File: ~/Teaching/intermediate-python-datasci/notebooks/<ipython-input-28-b89ab414a77b> Type: function
Look at the docstrings of two functions in Python -- you can check out pow
and enumerate
, for example.
What arguments do these functions take? Do any of them have default values?
Most, though not all, built-in functions have very descriptive docstrings that extensively document inputs, outputs, and functionality.
Here is a great guide to writing well structured and consistent docstrings.
def divide(dividend, divisor):
quotient = dividend / divisor
return quotient
What variables are the arguments? What variable is the return value?
Write a function cat
that takes 3 strings and returns those strings concatenated together with spaces between. E.g. cat('hello', 'friend', 'happy thursday')
would return 'hello friend happy thursday'
.
Update the function from #2 to give a default value for the third argument. Make the default value a period ('.'
).
Update the function from #3 to have a docstring. In one sentence, document what the function does.
Update the function from #4 to give a default value for the first argument. Choose any default you like. Does Python allow this? Why?
Occasionally, you may encounter a Python function that is created without using the def
keyword: lambda functions.
Lambda functions are one-line functions that do something simple, and are defined using the lambda
keyword.
A lambda function to add 5 to an input and return the result would look like
lambda x: x + 5
This means
"For any input x, return that x plus 5."
As you may have noticed, this function doesn't have a name -- we didn't use the define <function_name>
syntax.
Lambda functions are sometimes called anonymous functions because they don't have names.
Occasionally lambda functions can be handy, but there is no situation where lambda functions are necessary. For this reason, we recommend using named (non-lambda) functions until you've become very comfortable with functions in Python.
Are there any questions before moving on?