Going Beyond an Initial Python Script¶
Aimed at building a solid foundation of technical skills in Python to enable creating complex financial models solely in Python
Resources¶
Structuring a Complex Python Model¶
Notes¶
There are two layers of organization we should have in our Python models
The Python code itself should be well organized by using functions, which are self-contained logical units with inputs and outputs and optionally a description of what it does as well as the inputs and outputs
We can use Jupyter features to provide additional structure on top of this. The sub-problems or sub-models can be divided into sections using Jupyter markdown. A table of contents can be provided to easily navigate through the sections and to give an overview of the structure of the model.
The main inputs should be at the top of the notebook and the main outputs should be at the bottom of the notebook
Transcript¶
- hey everyone
- nick dear bertis here teaching you
- financial modeling and today we're going
- to be talking about
- structuring a complex python model
- as part of our lecture series on going
- beyond an initial python
- script learning python basics so that we
- can build out financial models
- using python so we've been working so
- far
- on this simple retirement model and we
- expanded it to
- a more dynamic salary retirement model
- in excel
- but so far as far as python is concerned
- all we've done is build out
- the most simplistic retirement model
- possible
- so we want to go to building the same uh
- dynamic salary retirement model in
- python as well
- uh but in order to do that we're gonna
- have to learn a little bit more of the
- python basics uh before we can really
- just
- jump right into that so that we don't
- get bogged down
- trying to learn everything all at once
- we can kind of learn the basic tools
- and then go and put together all those
- basic tools
- into the model that we're trying to
- build
- and then not only do we need to learn
- kind of you know the basic
- tools and and you know functions data
- types
- etc and python we also
- need to learn about a structure that we
- can use for our model
- uh that's going to make sense for
- someone that's coming to
- read your model that you know they can
- expect
- you know the inputs to be in a certain
- place outpost to be in a certain place
- and there would be a kind of a structure
- to it that is logical
- um so there's kind of
- um you know two layers to how
- we can structure our models
- in python so there's structure within
- basic python itself and we'll talk about
- how we can use
- functions to structure uh pieces of
- logic
- into kind of logical units and put those
- together
- to build the model but then also we're
- using jupiter
- on top of python to build out the models
- in this class
- so we can add additional structure to
- the model using
- jupiter because jupiter gives us that
- nicely formatted text
- we can basically create sections uh with
- that text
- to be able to differentiate the
- different parts of the model
- so when we build out a more complex
- financial model
- and this is you know a general kind of
- structure that we're looking at here
- it's not
- specific to python or excel or any other
- tool it's just kind of a logical
- structure we can use for our models so
- you know we've already talked about how
- you know a model
- basically just takes the inputs and
- ultimately converts them
- to outputs um and so
- up until now we just kind of think been
- thinking about the model as
- just this one block here without really
- thinking about how that model is
- broken down but as we dug into the
- uh excel dynamic salary model we
- found that really there were sub
- problems that we were solving
- inside the larger problem and so we
- formed
- uh you know sub models uh to deal with
- those individual parts of the problem
- and putting them all together uh made
- the entire
- model and then we can keep breaking it
- down even further
- you know within each of those sub models
- there were individual steps
- to carry out that part of the sub
- model so thinking about the dynamic
- salary model
- uh you know we uh ultimately our goal
- was to take
- you know things like the interest rate
- the savings rate
- uh you know the number of promotions et
- cetera
- um and convert that ultimately in a into
- a time until retirement
- and we broke that down into uh three
- parts
- uh one is to figure out the salaries
- over time
- one is to figure out the wealth over
- time and the last
- is to figure out the retirement details
- and so we split that down into three sub
- models just like is shown in this
- picture
- and then you know if we think about the
- um salary
- uh portion of the model that salary sub
- model
- we split that down into steps even
- further from there
- uh you know we calculated the cost of
- living factor
- separately we calculated the promotion
- factor separately
- and we ultimately got the salaries over
- time based on combining those two things
- so you know thinking of a model
- in this way is really helpful because
- you know when you just go
- and you have some problem and you need
- to go and build a model for it
- it can be very overwhelming on where do
- i even start on this thing
- there's you know so much involved here
- it's not clear to me how i get
- you know from the inputs to the ultimate
- solution
- well you just got to start breaking it
- down and try to
- work it into as many smaller sub
- problems as you can
- and then it all of a sudden becomes so
- much easier to solve these small
- sub problems like oh how do i calculate
- this you know cost of living
- adjustment factor that's a much smaller
- problem than this entire thing as a
- whole and so you can just take the small
- problems one at a time and that makes it
- easier to move forward on the model
- and then it's going to have a lot of
- benefits
- you know as i've mentioned people coming
- to read your model they can understand
- how it's laid out
- very easily and it becomes a lot easier
- to
- maintain the model going forward you
- know if someone
- needs to you know work on your
- uh salary portion of the model
- um you know now saying oh well there's
- gonna be
- uh recessions and whenever there's a
- recession they're going to stop doing
- the cost of living raises
- say that was our assumption uh then you
- know if you didn't have this structure
- everything was just kind of all in one
- then it would be not very clear where
- they would have to change things and if
- it would be
- you know breaking other things when they
- change it but if we've separated it to
- having the salary as its own sub model
- then they can just work on the salary
- portion of the model and not worry about
- how it's affecting the other parts
- as long as the inputs and the outputs
- remain in the same structure
- from that sub model so um
- a lot of benefits to using this kind of
- structure
- uh and so that's the structure we're
- going to follow in this class and i
- would recommend just in general
- for any financial model uh
- and then applying that to python we'll
- see uh
- more on the specifics as we uh
- you know dig into all these basics and
- then we actually go to
- implement that in the model but
- basically
- we can use functions to you to do this
- structure for us
- whereas in excel uh you know the model
- was the workbook
- right and then you know each sub model
- was a worksheet
- and each step was basically like a
- column and one of the tables
- for python it's all about functions
- so the entire model is going to be
- one single function you should be able
- to call a function
- give it your model inputs and get your
- model output
- but then each sub model is going to be
- its own function as well
- so then your main model function would
- basically just be calling
- each one of the sub model functions and
- then
- within each sub model function
- you can have a function for each step in
- the model
- so then each of these sub model
- functions
- is just calling each of the individual
- step functions to put it together
- and each of these individual steps
- functions
- actually have the main logic of your
- model and you can go to a dis
- additional levels of nesting if it makes
- sense for your problem you know you have
- you can break each of these steps down
- into even smaller sub steps
- and so on any number of layers is fine
- but this kind of functions inside
- functions
- is a nice way to structure things in
- python that
- that gets at this same kind of logical
- structure
- for the model so that's the basic idea
- behind structuring
- our python models and then you know you
- can also
- use jupiter to have you know the nice
- you know section headers and say you
- know this is the salary portion of the
- model and then it you know goes into all
- this part
- with the functions etc
- so with these ideas we'll make them a
- lot more concrete
- in the later lectures as we go to
- actually implement this
- um but that's where we'll leave it now
- for how to structure
- our python models so we'll come back
- next time to get started into the python
- basics as far as the syntax and
- different ways that we can work with
- python
- and we're going to be talking about
- conditionals in the next
- video so thanks for listening and see
- you next time
Branching Logic with Python Conditionals¶
Notes¶
Conditionals let you choose which logic to run based on some logical condition
This is just like using Excel =IF, but more flexible as we can run any arbitrary operation rather than just returning a single value
If/else if/else pattern becomes a lot more clear in Python as they are written as separate blocks rather than a nested =IF statement in Excel
Logical conditions are always evaluated first to True or False. If True, goes into if part, if False, goes into else part (if included)
Be careful about single = vs double ==, it is an easy mistake to make and you will get a SyntaxError applying the incorrect one
Elif is never strictly necessary but can help simplify the code substantially
The lab exercises test knowledge of conditionals but also build on our prior knowledge of for loops and show how they can be combined
Resources¶
Transcript¶
- hey everyone
- nick dear birdis here teaching you
- financial modeling and today we're going
- to be talking about branching logic with
- python conditionals
- as part of our segment of going beyond
- an initial python script
- how we're going to learn the python
- basics so we can build out complex
- financial
- models so we have
- talked a little bit about conditionals
- before in the class and that was in the
- context of excel before
- and we talked about the if function in
- excel
- and how that lets us basically check
- some kind of logical condition
- and then return one value if it that
- condition is true and return another
- value if that condition is false
- we have the same kind of um concept
- in python as well uh but it's even
- definitely more flexible in python
- um and you can do a lot more with it
- but it's the same basic concept we're
- gonna be checking some kind of
- logical condition and then we're going
- to do one thing if it's true and we're
- going to do something else
- if it's false so we can see
- um an example here on
- the slide and
- we can see um here
- an if statement if 5 is equal to 6
- then it's going to print not true
- otherwise
- else it's going to print
- else claws and
- it's a little bit covered here in the
- video
- but
- you can see that it gets else clause
- here uh coming up
- and that's because this logical
- condition here
- this 5 is equal to 6 that is not true
- right that's false
- that five is equal to six and because
- it's false
- it's not going to go into the if part of
- the logic
- it's instead going to go into the else
- part of the logic
- and that's why we get else claws here
- so this is the basic structure and
- you'll notice
- you know just like when we did the for
- loop
- in python that it has the same kind of
- structure here uh that we have the if
- and then we have
- a colon and then after that colon we
- have a level of indentation
- and then under that we have the logic
- which actually runs under the if
- part of the statement and then
- coming over to the else it's back over
- at the original
- level of indentation and then we have
- another colon
- and then uh another level of indentation
- back to
- indentation level one um or the logic
- that runs under the else clause
- the logic which runs if the logical
- condition
- evaluates to false
- so just like before you know we had four
- you know loop variable in uh list or
- whatever
- colon indentation and then the logic
- which runs under the four
- same thing here with the if this is just
- generally how you have
- uh you know blocks of logic in python
- it's going to be
- a colon to start that block and then an
- end in uh
- for all the logic which runs inside of
- that block
- so um you know obviously just comparing
- five to six directly
- is pretty meaningless right like that's
- always going to evaluate to false
- if it's always going to evaluate to
- false this uh
- code here will never run it will always
- just go to the else clause
- so we might as well have just not even
- had the if and just had the else clause
- right
- just just print else clause it would
- have been effectively the same thing
- uh but where it becomes more valuable is
- when you're actually using variables
- in these conditions and those variables
- could be coming through with different
- values
- so uh you know here we can do
- uh you know if this equals that and this
- and that are two different variables
- that we've defined
- and for now we would find them both uh
- to be the same value
- but you know setting it up this way you
- know you could easily define
- these as other values and then that
- would change what the logic
- is going to do down here
- so with here we have if this equals that
- and for now this and that have the same
- value
- and so indeed it's going to run the
- logic which is under this if the yes
- print me um and you'll notice for this
- one we don't have
- any else clause and that's fine the else
- clause
- is optional in python so
- you can just do an if and then run some
- code if it's true
- and then otherwise it's just going to go
- on it's not
- it doesn't have any alternative logic to
- use it's just going to continue on with
- whatever the next code is
- and then here we're looking at um you
- know if this equals 5
- this was defined the woo so it is not
- equal to 5
- and so it's not going to print this last
- statement here
- um it's just going to go on and
- you know continue with whatever code we
- have left in the program
- so that's the basic way that you use
- these conditionals
- in python and you know of course most
- the time you would probably be doing
- something more
- than just printing you can have as many
- lines of code as you want
- under any one of these as long as they
- just all keep that
- level of indentation um
- so arbitrarily any kind of code that you
- want to run
- under whatever conditions you can do
- that using
- these conditionals
- and you may have noticed that here we
- are using
- two equals whereas when we had
- assigned variables we are using one
- equals
- so that's the difference here in python
- a single equals assigns
- two equals compares so this is saying
- is five equal to six and this is saying
- this is equal to wu so subtle difference
- but it's just assignment versus
- comparison
- and you want to be careful about that
- because if you use the wrong one
- you're probably going to get a syntax
- error and then you're going to be
- scratching your head
- why is this not working single equals
- to assign double equals to compare
- so then
- we now have this else condition
- which we talked about here um
- and that we can think of just like in
- excel how
- you know in excel we had if logical
- condition and then value if true and
- then value at false
- so the else here is like the value if
- false in excel
- it's the logic which is going to run if
- the condition evaluates to false
- and unlike excel where we're bounded by
- you know you just
- get one value or you get another value
- here it's running any kind of arbitrary
- logic
- um so that you know can be absolutely
- anything and that gives us a lot more
- flexibility
- with the way that things are going to
- work in our models
- and then one other way to use these
- conditionals that we didn't look at here
- but we will look at uh when we go to the
- example
- in the jupiter notebook uh is elif
- which is shorthand for elsif um
- so that's saying you know that's you
- would put that after an if
- then next it would be elif or elsif um
- and that's just saying
- you know if that first condition was not
- true
- but i'm giving you another condition now
- if that one is true
- then uh execute this logic and we'll
- make that a lot more concrete here in a
- moment as we go through
- the example in the jupiter notebook
- so that's where we'll um jump off to
- that
- um we're gonna go into the python basics
- uh jupiter notebook which has
- uh you know more drawn out examples on
- all of this
- um so
- moving over to that um and this you know
- is broken up into sections matching the
- sections of the lecture
- we're going to use it in all the
- lectures in this segment
- so first here we're talking about
- conditionals
- so for conditionals um
- you know this is a little bit of review
- of what we just looked at
- but you know basically if whatever
- condition
- evaluates to true then it's going to run
- the logic
- which is under the if statement
- again that indentation is important if
- we leave that out
- we're going to get an indentation error
- expected and indented block
- because we had that colon we got to have
- the indent coming
- after that
- and of course if the condition evaluates
- to false
- then we're not going to get whatever
- code
- under here run um and here also show
- uh that you can have
- uh you know multiple um
- statements under here and they'll all
- execute you can have as many
- things as you want going on under here
- um so what's kind of going on in the
- background here
- is it always evaluates that logical
- condition
- first and evaluates that into either
- true
- or false so we can actually pull out
- that condition itself and see what
- happens
- when it's evaluated uh if we look at
- cat uh is he is you know comparing that
- cat that evaluates to true whereas we if
- we compare it to dog then that evaluates
- to
- false um so these true or false
- are what we call booleans that's another
- data type
- in python and it's just it takes on
- values of either true or false
- are the only two possible values for a
- boolean
- and so basically python evaluates this
- and then you know as it's executing it
- it basically
- substitutes that and so now we're down
- to if true
- which it will always execute this it's
- gonna print got a cat or
- uh you know in this case it was
- evaluating cat
- is that equal to dog that evaluates to
- false and so it's not going to print
- uh got a cat
- um and again as i mentioned before uh
- single equals uh defines
- double equals compares so here we use
- the single equals
- and that's defining a to be equal to 5
- whereas double equals is comparing this
- is saying
- is a equal to 5 yes that is true
- is a equal to 6 no that's false because
- a is equal to 5
- which you see here
- and if you try to use just a single
- equals in the condition
- then it's going to give you a syntax
- error
- again a syntax error just means python
- doesn't understand
- what you're trying to do you didn't
- specify things in the correct way
- for python to understand it so because
- you're saying
- if a is equal is defined to equal five
- that doesn't make sense it's expecting
- to see a logical condition
- not an assignment um and so that's why
- it breaks here uh if you just use a
- single equals
- as soon as we put that double equals i
- have it right here
- uh then it will execute just fine
- so that's the basic if then we can go to
- using else
- as well so
- you know the else is going to run if the
- condition
- is false so
- here i'm defining my my variable to be
- abc
- if it's equal to nope which it's not
- that evaluates to false
- uh since it's false it's going to go
- into the else clause instead of
- into the if clause so that's why we get
- runs if condition is false from the
- output
- um and again pay attention to those
- levels of indentation
- it's you know if colon
- indentation logic that runs under the if
- and then
- back on to the last level of indentation
- else colon and then
- up into another level of indentation for
- the logic which runs as part of the else
- uh if you mess up any of these you know
- say you forgot that else
- should come back um you're going to
- again get a syntax
- error because it does not understand
- what you're trying to do basically this
- else is now
- coming from nowhere it doesn't
- understand that it's related to this
- if by having them on the same indication
- level
- then it is able to understand that uh
- this else is attached
- to this if
- um and so
- you know here same thing uh now looking
- at if it's abc which it was we defined
- it to be abc
- um so that's why we go into the if
- clause logic now
- rather than the else clause that we did
- back here
- so then this uh section here
- is about elif or elsif
- and so you don't really ever necessarily
- need
- to use e-lif it's really just
- a convenience thing um to make yourself
- not have to write as much logic
- and so here's the basic idea of an
- example where you might
- want to use elif
- and that's you know we've got uh you
- know
- whatever possible prices coming in we
- want to basically classify that
- into uh you know is it cheap is it
- mid-range is it expensive uh is it
- negative such that they're actually
- uh paying me rather than me paying them
- um
- so that's the idea here so um
- we run this uh price is a hundred and we
- get it's priced into the mid-range
- so how do we get there so it first
- starts if price is equal to zero
- well 100 or is less than zero price is a
- hundred so that's not
- less than zero that's false and so it's
- going to go to the next condition
- so now we have elif so that works kind
- of like an
- else that it builds off of the previous
- if but also it checks another condition
- so uh the price was not less than zero
- and so we're going to come here and then
- we're checking
- is the price less than 50. so that's
- basically saying that the price is now
- greater than zero
- greater than or equal to zero but less
- than fifty
- it's in that range of zero to fifty and
- if that were true
- then it would print it's pretty cheap
- but again a hundred is not less than
- fifty this evaluates to false
- and so it's again going to go on to the
- next statement
- um here you know else
- going off of this uh if and
- now it's saying you know else basically
- the price is
- greater than or equal to 50 because it
- has failed both of these conditions
- uh then also if
- that price is less than 150 then it's
- going to be priced in the mid-range
- so 100 now actually is less than 150
- and so that's why we're going to end up
- in this
- statement and then you'll notice that we
- only get that statement
- because now this if has evaluated to
- true
- and so the else clause is not going to
- execute
- because now we did get a condition that
- was true
- and so it's not going to go into the
- else the else is only
- if the conditions were false
- so if we did put the price as 200 then
- we are going to get up here
- into the else clause because here it
- wasn't less than zero it wasn't less
- than 50
- it wasn't less than 150 all those
- evaluated to false
- and because they have all evaluated to
- false we came into the else clause
- or it could be negative we end up here
- because we hit this first if condition
- the price is less than zero
- so we're here and then all of these are
- else based
- and so they're not going to run if the
- first
- if the prior condition was true um and
- because the first condition was true
- then we don't even evaluate any of these
- we just hit here
- and then it goes on after this block
- after that
- the else and the e-lift are only going
- to execute
- if the prior condition is false
- so the reason that i say that this is
- really more of a convenience thing to
- make your code simpler
- uh is that uh you know this code here
- does the exact same thing we can see a
- hundred gets into the mid-range
- we can see that 200 uh gets too
- expensive
- we can see that negative 10 gets us to
- you're going to pay me et cetera
- but we can see that the code is a little
- bit longer here so here we didn't use
- any else
- any e-lif we just did it all with plain
- if conditions
- but what we had to do here was here we
- could just
- you know knowing that it was already not
- less than zero
- we could just check if it's less than
- 50. but here
- each if is totally separate it knows
- nothing about
- any of the prior ifs and so we need to
- check all the conditions in each one
- so here now this has to be
- if the price is greater than zero and
- it's less than 50
- in other words it's in this zero to 50
- range then we're going to print that
- so you need to put both sides of this
- condition because we can't
- count on it's only going to get here if
- the prior condition failed
- because it's going to actually execute
- all of these conditions and potentially
- all of the
- statements if those evaluate to true
- um so that's you know kind of the basics
- on conditionals
- in python and then looking at the lab
- exercises so you're going to be using
- this same
- jupiter notebook for all the lab
- exercises in this
- segment and so here
- we have three exercises on the
- conditionals
- and these exercises
- you'll notice also build off of some of
- the material that we've already learned
- you're going to have to you know use a
- for loop for some of these exercises
- so you know everything in the course
- kind of builds on each other until
- ultimately we can
- build complex financial models
- so you know that concludes uh the
- material on conditionals
- and we're going to come back next time
- to
- talk about grouping objects together
- using
- lists so thank you for listening and see
- you next time
Grouping Objects with Python Lists¶
Notes¶
Lists are one of the basic container data types in Python. They hold other objects so we can work with them as a group
Lists hold objects one by one in order and objects can be looked up from the list using the numeric index of the object
It is a very common pattern to create an empty list, then go through some logic in a loop to create the object you want in the list and add it in each run of the loop
This numeric index is zero-based, so look up the first object by 0, the second object by 1, and so on.
We can pass a slice to get a group of objects out of the list as a new list or a single integer to get a single object out of the list
Negative numbers means count from the end of the list, -1 is last object, -2 is second to last object, and so on
Objects can be added to the list when it is created, but also later on using .append and .insert. Objects can be removed using .pop
Lab exercise 1 tests list building for loop pattern, 2 tests adding objects to lists, and 3 tests list indexing and slicing
Resources¶
Transcript¶
- hey everyone
- nick dierbert is here teaching you
- financial modeling
- today we're talking about grouping
- objects together
- with python lists this is part of our
- segment on going beyond an initial
- python
- script how to uh you know learn the
- python basics so that we can go
- and build out financial models using
- python
- so we have talked a little bit about
- lists
- in the course already but now we're
- going to
- learn a little bit more about working
- with them
- and some of the useful patterns uh using
- lists
- so um we already learned that
- lists are one of these uh kind of
- container data types
- in other words it's uh an object that
- holds
- other objects within it um
- and so here uh you know as we start to
- look
- at this example uh we can see here the
- inputs
- uh one two three we have the uh
- numbers one two and three stored within
- this list
- uh which we're calling inputs
- and so these lists allow us to group uh
- this one two and three together
- into a single variable that we can then
- uh you know do other things with and
- so a very common pattern in python
- and in a lot of programming languages is
- uh to create
- a list an empty list before
- a loop and then as you go through the
- loop
- you add items to the list to build up
- the list
- through the loop so
- you know here we're looking at you know
- basically
- we want to take our inputs and we want
- to add 10
- to the inputs and
- have the outputs be just you know each
- of the inputs
- with 10 added to them
- and so this pattern accomplishes that
- and that we have the for loop here and
- the for loop
- is going to go through each one of these
- inputs one at a time
- pulling each one out and as we go
- through we're going to be adding 10
- to whatever that input is and then
- we're going to be appending that value
- onto the outputs list so this append
- is a new function that we're learning
- about here
- a pin just adds an item onto the end
- of a list so this list was empty to
- start with
- but as we go through we're going to add
- each input
- plus 10 into the output list
- so then at the end of that we would have
- 11 12
- 13 in the list and then this last part
- here
- is just showing another way that you can
- add items into a list
- because append will always put the item
- at the end of the list
- insert allows you to put the item at any
- position
- in the list so here we want to insert
- the this a as the first value here in
- the list
- and so that's why when we take a look at
- what
- the resulting list is
- then we get uh a first and then
- 11 12 13 which was the original list we
- had
- from this part of the code
- and you may be wondering why it's zero
- to insert this a at the beginning
- and that gets into zero based indexing
- in python which we'll talk about
- here in a moment
- so uh you know one other very
- commonly used functionality of lists is
- indexing and slicing lists
- so that allows you to pull certain items
- out of the list so you can either pull a
- single item
- out of the list by its position in the
- list
- or you can pull out a whole uh you know
- sequence of items
- uh by again their their indices
- in the list um
- so here you know we're looking at an
- example of
- my list having a b c and d in it
- and now we're going to look at how we
- can index that list to pull certain
- items out of it
- and so here's where i'm coming back
- around to the
- zero based indexing in python
- so zero is going to get us the first
- item
- in the list here if we do my list
- bracket zero
- that gets us a if we do my list brackets
- one
- that gets us b and so that is definitely
- counter-intuitive
- um for a lot of people but this is the
- way that the majority of pro
- programming languages work that indexing
- is zero based
- zero is going to give you the first item
- one is going to give you the second item
- and so on um
- and we'll talk a little bit more about
- that
- when we look at the jupiter notebook
- example
- then also you can count backwards from
- the end of the list
- um so -1 any negative number is going to
- be counting from the end
- of the list so minus one is going to get
- you the last item in the list
- here that's going to be d um if you did
- minus two that would be the second to
- last
- item in the list so that would give you
- the c
- and then uh that's indexing and then the
- other part is slicing we're slicing we
- grab
- multiple things out of the list at once
- and it gives us a new list
- which has a subset of the objects which
- were in the original
- list so here
- the slice is defined by the colon
- having a colon in here and so
- when you slice it's uh
- you know the full format is um
- you know from this item uh up to
- but not including this item uh before
- and after
- the column so slicing from
- one to three again one
- is uh talking about the second item
- remember because of that
- uh zero based indexing
- and three is talking about the fourth
- item so it's
- from the second and up two but not
- including
- the fourth item so that means we get the
- second and the third item
- as a result
- but either side of this
- slice is optional and
- if you exclude it it's just going to go
- to the end of the list in that direction
- so having nothing on this side
- and then up until but not including the
- last item
- that's going to be every item in the
- list up until the last item so just
- chopping the last item
- off of this list whereas
- if we uh you know before the colon we
- specify it but after
- the colon we don't that means it's going
- to go all the way to the end of the list
- for the right hand side but for here
- we're going to start from index 1 which
- is the second
- item so this is going to be every item
- from the second
- going all the way until the end of the
- list so that's why we get
- bcd as a result of this
- so you can use this to grab whatever
- objects you want out of your list
- so let's go ahead and jump over to the
- jupyter notebook example where we'll
- look at these things in a little bit
- more
- detail so
- um you know first let's hear just look
- at a list um and so
- we define lists using these brackets uh
- when you just have
- brackets out here on an assignment uh
- that's saying i want to make a list
- and when we look at what that list is
- we just see brackets here again
- representing that that
- is a list and if we check the
- type of that then we are and
- going to indeed see that it is a list
- um and so
- you know we have this list and we know
- that it's empty
- right now but we can
- add items onto a list
- using append so here we're going to
- append
- five and then we're going to look at the
- list again
- and now what might be a little
- counter-intuitive to people
- is now you come back over here and you
- check this again
- now all of a sudden it's changed now it
- has five in it and that's because
- we modified the same list to add five to
- it we didn't
- uh redefine a different list uh which is
- going to be separate from what was up
- here it's the same list
- and so if we just run that code again
- then we're going to see it's actually
- changed and now has a five
- in it and then as we go and add
- additional items
- they always add on to the end so we
- append six and then we append seven
- now we have five six and seven and the
- list
- which again you know carries through to
- anywhere that you're using
- this same list
- um so that's also gets into another
- pitfall that a lot of people hit
- as they begin to build things out in
- python and jupiter
- is the execution order of your cells
- can actually change the results that
- you're gonna get
- uh as you saw before when i first went
- through
- and i ran this my list was empty and now
- that i come back and run it
- my list is 567 and so if you run your
- cells
- in different orders you get different
- results and so
- um you know definitely as you uh
- you know get things working in your
- model you want to often just
- restart kernel and uh run all cells
- that's gonna give you a new session and
- just start everything
- run everything in order and that way
- you'll be sure that it's gonna execute
- exactly like when someone else is going
- to be running your model
- so then getting
- into uh talking a little bit more about
- indexing again we have this
- zero based indexing zero gets you the
- first item
- one gets you the second item um etc
- uh you know going all on to whatever
- number when i get the 10th item just put
- in x9 just subtract one from whatever
- the index is and if you want to
- understand more why most programming
- languages
- uh set it up this way i've included a
- resource
- here where you can read a lot more about
- that
- but that's definitely outside of the
- scope of this class that's more of a
- computer science concept
- uh all we need to know is that it is
- zero based indexing
- we do put a zero if we want to look up
- the first item
- for our purposes we don't really need to
- know why but for the curious people i
- just added that here
- um so then we're jumping back into
- adding items to lists but looking at the
- insert
- function method instead of the
- append method of the list
- so append again always puts the item at
- the length at the end of the list
- whereas insert will add it into any
- position
- um so again we're working with this same
- uh
- my list that we had from before
- 567 in it right now
- and now we're going to insert uh
- at the position 0 at index 0 which would
- be the first item
- we're going to insert woo and so then
- when we do that and we look at the
- result
- then we're going to have first woo and
- then our original
- 567 and you can insert
- at any position within the list so here
- i want to insert at the second
- position or sorry index two which would
- be the third
- uh object in the list i'm gonna insert a
- ten
- and so indeed then you see the third
- item in the list here
- is indeed a ten so whatever uh
- index you put here it's going to put
- that
- item that object at that position
- in the list
- so then we can look at using indexing
- and slicing to look up items within the
- list
- so again 0 is going to give us the first
- item
- here the woo 4 should give us the fifth
- item
- in the list which indeed it does
- um now if you put an index
- that does not exist in the list then
- we're actually going to get an
- error from that so here i'm trying to
- look up these
- the thousand and one item in the list
- and when i do that then i get index
- error list index
- out of range so the error is telling you
- exactly what happened here
- the index that you passed on this list
- is out of the range of possible
- indexes on this list right zero
- should work one should work two three
- and four
- are the possible indexes here as soon as
- i go to
- five then i'm going to start getting
- that index error
- so you have to actually put an index
- which exists within the list
- or otherwise you're going to get this
- index error now the one you know
- somewhat exception to that is you can
- use negative numbers
- um to index the list as well
- and that's going to count from the end
- of the list
- so minus one is going to get you the
- last item in the list
- which again my list looks like that we
- are getting the last item here
- and negative two is going to give us the
- the next last item
- in the list um and
- this index error can come up in the
- other direction as well
- we try to look at you know a thousand
- uh items before the end of the list
- that's you know way beyond the beginning
- of this list so once again we're out of
- range
- and we get an index error
- so that's indexing about pulling a
- single item
- out of the list now we have slicing
- which pulls multiple
- objects out of this list and creates a
- new list
- from those objects so here
- remember again slicing is really defined
- by this colon
- and that colon means i want to get from
- index one up until not including
- index three and so that's from the
- second item
- up until but not including the fourth
- item
- so again showing what my list is here
- and i run this so i want to get from the
- second item
- up until we're not including the fourth
- item i get the second item
- up until but not including the fourth
- item so that's why we get
- five and ten here
- um and leaving either side of the colon
- empty again we'll just
- uh you know let it continue all the way
- to the end of the list
- in whatever direction so leaving the
- right side of the colon
- empty will go all the way to the end of
- the list leaving the left side of the
- colon empty we'll go all the way to the
- beginning of the list
- and so this is saying from index one
- until the end
- which means from the second item until
- the end
- and that's why we get this portion of
- the list
- and then this one says uh
- you know all the way from the beginning
- of the list up until
- the but not including the last item in
- the list
- and so that's why we get everything
- except for this last
- seven in the list here
- [Music]
- and then the lab exercises here
- would be the working with lists section
- of the
- lab exercises and so
- this is going to test a few different
- things uh
- the loop building pattern uh adding
- objects
- in the list and also indexing and
- slicing
- of the list as well um
- so that concludes our section
- on python lists and grouping
- objects together using them next time
- we're going to come back to
- instead group logic together instead
- using functions thanks for listening and
- see you next time
Grouping Logic with Python Functions¶
Notes¶
Functions are the logical building blocks for any Python program, including our models
Functions contain a piece of logic which then can be reused flexibly with different inputs
We have functions in Excel, e.g. =SUM, =IF, =VLOOKUP, but as an Excel user you typically do not define functions. Python has built-in functions and also it is very easy to define your own.
Ultimately, you should be able to run your entire model by running a single function
The sub-models should also be functions, and the steps within the sub-models should also be functions. This can be broken into as many layers as is necessary. Your higher-level custom functions will be calling your lower-level custom functions.
Not only will you have better readability and organization of your model, but also you will be able to reuse logic more often which lowers maintenance costs
Functions scope the variables defined within. You cannot use those variables outside the function. This lets you use more general variable names which increases readabilityDefault arguments are a great way to keep your function flexible but also easy to use
For these lab exercise, I have provided cells to check your work. After adding your solution and running the exercise cell, then run the check cell which will throw an AssertionError or NameError if incorrect and nothing if correct.
The exercises test creating functions with and without default arguments and adding docstrings to functions
Transcript¶
- hey everyone
- nick dear bertis here teaching you
- financial modeling and today we're going
- to be talking about
- grouping logic together with python
- functions
- this is part of our lecture segment on
- going beyond an
- initial python script and this process
- of learning the python basics so that we
- can
- build out complex financial models using
- python
- so we talked a little bit before
- about how functions are going to become
- the logical structure
- to build out our model
- and that we're going to use functions
- to uh you know define the entire model
- should be a function
- and then each sub model should it be a
- function
- and each step within the sub model
- should be
- a function and this could continue going
- to additional levels of nesting
- as necessary whatever is appropriate for
- the problem that you're working on
- so each uh you know layer of the model
- is going to be a function and those
- functions are going to call the lower
- level functions
- to ultimately build up the entire model
- and going to this kind of structure
- means that
- things are a lot more contained it's a
- lot easier to just work on one part of
- the model
- and not worry about affecting other
- parts
- and it means that you're going to be
- able to reuse more of your code
- and it's going to be easier to read your
- code and there's lots of other
- advantages here
- in structuring the model in this way but
- in order to
- add that kind of structure we're going
- to have to learn how to
- work with functions in python how to
- define them how to use them
- and let's go ahead and dig into that
- so a function is basically
- just a lot a logical
- construct where it's just a group of you
- know statements of code
- that describe some logic and that logic
- you know may have inputs it may have
- outputs
- and we give that function a name uh so
- that we can call it by that name
- so you know it can take uh you know what
- was
- you know maybe you know thinking about
- our uh dynamic
- salary retirement model you know this
- part where we have to
- calculate the promotion factor year over
- year
- uh there's a few things going into that
- you know figuring out
- uh is this a promotion year how many
- promotions have occurred
- up until this point etc
- you know all that can just you know
- basically get wrapped under one function
- you know like calculate a promotion
- factor could be the name of that
- function and then you know as someone
- using that function or you know as
- you're building your model
- then you just call this create
- promotion factor and that's going to
- make the factor for you
- running all of that you know individual
- lines of code
- that actually carry that out so then
- we've reduced
- you know calling all these individual
- lines of code to
- a single line of code of calling this
- function and we've also
- given it a nice indicative name which
- describes exactly what it's doing
- in the context of our model rather than
- just having individual lines of code
- so it can definitely help a lot with the
- readability and structure
- of your model
- and you know going even further than
- that you can also
- add documentation to your functions it's
- called a doc string
- and that is just
- a string that goes along with your
- function which describes what it does
- and that is just another way to make
- your model even more readable
- because there's a lot of explanation of
- how things are working all the various
- steps
- um and then i've said before you know
- everything is an object in python
- functions are
- objects as well um and so
- you know that is probably not going to
- uh be too important for you as far as
- this class
- um but just know that they are treated
- like any other object
- and so you could um you know do things
- like how
- you could have a list of functions um
- you know you can pass functions as
- arguments and other functions
- there's tons you can do here python is
- very flexible
- by treating everything as an object
- so here's an example function here
- and you'll notice that there's a couple
- parts going on inside this function
- so one thing that you may notice
- initially is kind of this
- familiar structure that we had with the
- for loop we had it with the if statement
- and the else and the elif
- uh that we have some kind of statement
- and then we have a colon
- and then we have indentation and then we
- have logic that goes under that
- so again this is you know the common way
- that
- uh you know logical blocks are defined
- in python
- you have a colon and then you have an
- indent
- and so it's the same here for defining a
- function
- so defining a function that's uh going
- to start with a def
- you know just like a four leaf starts
- with a four and if statement starts with
- an if
- defining a function starts with a def so
- that's the first thing we'll see here
- for defining the function and then after
- that
- it's the name of the function whatever
- we want to call it
- uh you know it can be anything that
- describes what the function
- is doing um but it cannot have spaces in
- it
- we use underscores instead of spaces and
- typically people will make these
- uh as well so lowercase and underscores
- where you would normally have spaces
- so that's the name of the function and
- then we've got to have a parenthesis
- and then after the parentheses the open
- parenthesis then we define the arguments
- of the function so these are the inputs
- this is what we're going to be able to
- pass into the function
- um we're defining that here and so i
- said before you know it can have inputs
- it can have outputs
- it is possible to define a function
- without inputs you would just have open
- close parenthesis here
- instead of having things in here but
- this function here does have inputs
- it has three inputs a b and c
- and uh we'll notice a and b are there
- uh just by themselves and then we have c
- equals ten
- and we'll talk about what this equals
- ten means
- here in a moment but for now you know
- we've got three arguments three inputs
- to this function uh they're each going
- to be separated by commas
- and you're giving the name of each
- input uh here and then when you're done
- adding all the inputs then you put the
- closed parenthesis
- and then we have the familiar colon or
- after the colon
- then we've got to have that level of
- indentation and then at that level of
- indentation
- then we define the logic for the
- function
- so this can be absolutely anything that
- happens within the function it can be
- running whatever lines of code you want
- it can be calling other functions doing
- whatever
- uh you know for loops if whatever kind
- of logic you want to have in there
- and then at the end
- if we want to have an output from the
- function which most functions do have an
- output
- then we're going to want to return the
- result from that function so whatever
- you return
- is going to become the output of the
- function
- so what this function is actually doing
- is it's adding together
- the three inputs um and then returning
- that as the output
- so really it's like a sum function it's
- just summing up these three
- inputs that we can give to it
- and then it takes that sum and it's
- going to return that
- it's going to make that the output of
- the function
- so uh you know you're always going to
- have
- kind of two parts with functions the
- first
- is defining the function and then the
- second
- is using the function so defining the
- function
- no nothing actually happens like no
- computation is actually done
- after you've defined the function it's
- only when you use the function
- that is going to run the logic which is
- inside of the function
- so you define it one time and then you
- can use it
- as many times as you want so we could
- keep calling my funk again and again
- with all sorts of different inputs and
- get all sorts of different outputs uh
- as long as we defined it one time at the
- beginning
- and you have to define it before you can
- use it otherwise python is not going to
- know
- what you're talking about when you say
- myfunk you have to
- first define myfunk so that it knows
- what you're talking about
- and when we call a function uh then it's
- the name of the function the same name
- that you defined
- and then it's an open parenthesis and
- then we're going to pass
- the arguments to the function the inputs
- to the function and then we're going to
- close parentheses
- and that's how you call the function and
- each of those inputs is going to be
- separated by a comma
- and um you'll notice that we put in 5
- and 6 here
- and we get 21 as a result so how do we
- get to 21
- when we're just putting 5 and 6 in here
- it's supposed to be adding up the
- numbers
- well that brings in this last part here
- where we had to find
- c equals 10 in this last part of the
- function
- so that's what's called a default
- argument
- for this input c
- so c is going to default to 10
- whenever c is not passed so
- this is saying that 5 becomes a 6
- becomes b
- and then c is going to take its default
- value of 10 because we didn't pass
- anything else here
- and so that's why we get 5 plus 6 plus
- 10
- is equal to 21. so whatever
- you're passing as your inputs to the
- function
- then that's going to basically come
- inside the function
- that you defined and those values that
- you passed are going to take on the
- names
- of the inputs that you've defined here
- so this 5 becomes a
- this 6 becomes b and c uh
- you know takes its default of 10 going
- into the function
- but an important thing about functions
- is that those names those variables are
- scoped
- to the function itself and so if you run
- my funk 5 6 and then after that you say
- you know what is a you try to print out
- a it's going to give you a
- you know name error a is not defined and
- that's because
- a is only defined within this function
- as soon as you leave the function it's
- no longer defined
- and so basically you call this and then
- you've already defined my func
- and so it knows python knows now that my
- func basically means execute this thing
- and so it's going to go inside this
- thing and then as long as it's inside
- this
- a b and c have meaning they're defined
- uh but as soon as it returns and it
- leaves this function and we come back
- out to here and get 21
- then these a b and c are no longer
- defined it has onset
- those variables so that is definitely
- a gotcha for people just getting started
- to use functions they may try and use
- the variables which are inside of
- functions
- whereas those say within the function
- but
- as you get more comfortable with the
- stuff it's definitely a
- feature of functions because
- what that allows you to do is use much
- more general
- naming for things um you know you still
- want to use
- names which are indicative of what the
- input actually means
- but it saves you from having to keep
- coming up with different names more and
- more
- because that name is just going to last
- for the function
- and then it's not going to be used
- anymore and that frees you up to again
- use that same name
- in a different function without either
- of them
- conflicting with each other
- so that's the basic idea with functions
- let's go ahead and
- look at some examples in the jupyter
- notebook
- so again uh function is just taking a
- logical process
- and wrapping it up into a unit
- um so um
- we've talked about how we want to
- structure our model
- and you know basically layers of
- functions um
- but let's just say you know not even
- thinking about the full structure of the
- model
- you're just writing out some code and
- then you find yourself
- taking the same code and then copy
- pasting it and changing a little thing
- and then copy pasting it and then
- changing a little thing
- that should definitely be an indication
- to you that you should be using a
- function
- for this now the function is going to
- save you from
- from just copy pasting that code
- having basically you know really
- repetitive code
- functions can avoid that
- and that's definitely really useful to
- have
- because it really helps with the
- maintenance of your code over time
- if you copy paste a whole bunch of code
- and then
- you know you've got the same basic code
- copy pasted 100 times
- and then you realize you need to change
- one little thing about that code
- you've now got to go and change it in a
- hundred places right
- whereas if you wrote one function that
- does that logic
- and then you called that function 100
- times in a loop or something like that
- so it's really just a few lines of code
- you just change that one function and it
- makes that change carry through
- to all the usages of the function all
- those hundred usages
- and so now it becomes way easier to
- make changes to the code because it's
- going to flow through
- to all the different parts of your model
- so this will definitely become more
- concrete if we look at an example
- of this um so here
- we've got an example of
- um and we've got you know some prices
- uh for three different stocks in three
- different lists
- and we want to get some summary
- statistics on those
- prices um and so
- you know we want to uh figure out
- you know what was the last price what
- was the average price what was the max
- and the minimum price
- out of the prices that were given so you
- know you might
- you know okay i have prices apple i go
- and write out this code
- um that the average is you know the sum
- over the length
- um we take the max we take the min
- um to get those and we
- um take the the last one in the list to
- get the last price
- and then we print that all out in a
- string right um
- and that's all well and good as long as
- we're just doing this
- one time but then we have to do the same
- thing with microsoft and we have to do
- the same thing with
- amazon so you might think okay we'll
- just take this whole thing copy paste it
- and let me just change aapl to msft
- now and you know just keep doing that
- and now we've got basically three blocks
- of
- pretty much the exact same code just
- changing out the variable names
- each time and so then
- you know we think about we want to add
- the standard deviation now to this
- okay well now we have to add that in
- each one of these we have to add the
- standard deviation three times which is
- going to be a big pain
- also this is just really repetitive to
- look at um
- and it could be easy just to you know
- make a mistake in just one of these
- and then you uh could easily miss over
- that because it's just in one of them
- and not in all of them
- so there's a lot of drawbacks to having
- this kind of approach
- so if you you know start to feel your
- code getting like this
- then you should think about
- restructuring that code
- and so we can restructure that using
- functions
- so now here instead we have
- a function price summary statistics
- that is going to do all this for us
- and so for we're going to define
- the function price summary statistics
- that's the name of the function
- and it's going to take prices and it's
- going to take the ticker symbol
- um and then here next you can see
- this is that documentation that doc
- string
- that i was mentioning which describes
- what the function
- does so for docstring you
- triple quotes and then you put the
- description of the function
- and then you do another triple quotes
- and you can have this split on as many
- lines as you want that's fine
- by doing the triple quoted string that
- makes it a multi-line string
- so that you can have this kind of format
- so here we're describing the function to
- say it takes the prices and the ticker
- and then it prints the summary
- statistics so already
- you know this code is starting to get a
- lot clearer because
- you know we know that this is doing
- price summary statistics
- we have a description of what it's doing
- um
- and this code is definitely less
- repetitive than what we were looking at
- before there's just less code
- going on here to understand so
- uh then we have basically the same code
- as you know one of these blocks from
- before
- but it's even become a little bit
- shorter because we didn't have to do
- you know prices apple prices microsoft
- we could use a more general prices name
- uh you know again this is the advantage
- of that scoping the names
- uh that this prices is only going to be
- defined within the function
- and so when we run this for apple versus
- running it for microsoft versus running
- it for amazon
- this prices variable is not going to
- conflict uh
- it's just going to you know when we run
- it for apple it's going to
- you know be the prices apple which is
- taking its place when we run it for
- microsoft it's going to be prices
- microsoft taking its place
- um but we can just write prices here
- um and it becomes a more general name
- and that makes this thing easier to read
- so then we've got all the same basic
- logic here
- just shorter names it's a little bit
- easier to read
- and definitely a lot easier to read with
- the name of the function as well as the
- description of what it does
- and then we want to use this function to
- get the summary statistics
- on each of these stocks so that's where
- uh you know i'll go ahead and uh let's
- just say we didn't have that at first
- you'll see i run that and it does
- nothing right we get no output here
- and that's because all we've done is
- define the function
- we haven't actually called the function
- to use it
- uh so that's this other part here is
- then
- actually using the function actually
- calling the function
- and so that's where we put the name of
- the function the same name
- that we defined and then we put a
- parenthesis
- and then we pass whatever arguments and
- then a closed parenthesis and that's how
- you call
- the function um
- and so um here we're first
- passing price is apple um
- and the ticker symbol aapl
- and so that's going to come into this
- function uh so let me
- remove these at first we're just looking
- at the apple part so now that's going to
- take
- prices aapl which is all these different
- prices
- and now python knows because we defined
- price summary statistics it knows that
- this means okay i'm going to come into
- here
- and now prices aapl is going to become
- prices
- so for the scope of this function as
- long as we're executing this
- now the apple prices have become the
- prices
- and the apple ticker has become the
- ticker and so that's why we see
- uh you know all these apple uh specific
- stuff here
- even though we're using a general code
- um
- and then uh you know looking at the
- other two
- you know same thing we passed the
- microsoft prices and microsoft and we
- passed the amazon prices in amazon
- and that's why we get uh you know the
- statistics
- specific for those particular stocks so
- putting it all together
- then we have all
- three summary statistics here
- and if you're worried about the
- repetition of you know typing this
- three times you can go a little bit
- further with this
- you know you could create an all prices
- which actually has
- uh you know the uh the apple prices
- and then the microsoft prices
- and then the amazon prices
- and then you can you know create the
- tickers
- list which has aapl it has uh
- you know msft it has amzn
- and then uh you know instead of this we
- could do
- uh you know four uh
- for price list
- uh sticker symbol and
- uh we'll learn more about this zip later
- that lets you loop through
- uh two lists at once uh you could do
- that
- and you could uh then indent this and we
- can put
- uh this price list here and we can put
- this uh ticker symbol
- here um and then we would get the same
- output from that um so then that becomes
- even a little bit more general you can
- continue to add more price lists and
- tickers in here and it's just going to
- continue to add the output on there so
- definitely that second pattern was a
- little bit more advanced
- but you'll be more comfortable with
- these things as we progress
- throughout the course um
- so that's kind of the motivating example
- on why we might want to use functions
- uh now let's go to uh
- digging a little bit more into detail of
- how we actually use them
- so again first to find the function then
- use the function
- so here we're just defining uh nothing
- nothing happens as far as you know any
- kind of output or code getting executed
- it's just defined
- now python knows that atom
- will take two inputs and add them
- together
- and then return that as the output um
- so then we add them of two and five and
- that will give us
- 7 so that makes sense it added those two
- numbers together
- and the return is important here to get
- that output
- outside of the function if we had it as
- just
- you know atom is a plus b uh
- then we run this you'll now see that we
- have no result
- uh coming out of the function right
- because we didn't return it
- so it's not able to come outside of the
- function
- we need to return it to actually get it
- as output
- for the function
- so then you know that can definitely
- confuse people a little bit with
- uh you know you bring in print so you
- know when you print something
- it's going to show it um but that
- doesn't mean that that value is actually
- coming outside of the function uh the
- variable
- is gonna stay scoped to the function if
- you don't return it
- then uh you know that value is gonna be
- gone
- even though you already printed it um so
- here is just a function that always
- returns
- five um but you know whatever you get
- whatever you pass to it it's going to
- add 10 to it and then it's going to
- print that
- uh but then it's ultimately going to
- return five
- so you run this and you see my value is
- 110
- but then you see five so the result that
- actually
- came out of that uh is five because we
- returned five
- and then you'll notice now if we try to
- look at my value
- even though it was already printed out
- here and it worked fine
- now we get name error my value is not
- defined
- and that's because my value is only
- defined within this function it's scoped
- to this function and so within
- return 5 you know anywhere inside this
- logic we can use
- myvalue and it will work just fine
- but then as soon as we come outside the
- function we can no longer use
- myvalue or any other variables which are
- defined
- as part of that function or the inputs
- to that function
- they're just temporary temporary
- variables which last only for the
- function
- body
- then we can add a description
- of what our function does and that's
- called a doc string
- um so when you you know type out your
- function
- and you know it takes some values then
- you get to here
- uh if you start typing you'll see once i
- type the third
- quotation mark it actually
- auto-completes the rest of that it knows
- i'm trying to do a triple quoted
- uh string and then i just hit enter a
- couple times
- and then i can go ahead and type my
- description
- so that's what we've done here
- is describe this function it always
- returns 5 but it will also print
- my value plus the past
- you know 10 plus the past value um
- so that now is the description of what
- it does
- um so that serves a couple purposes
- one is that you know you just see the
- function in there uh
- as you're just reading through the code
- as someone who's trying to understand
- the model
- and you have a description you can you
- know see in plain text
- what that's actually supposed to be
- doing without having to understand the
- code at a great level of detail
- but the other thing which you know we
- won't necessarily
- uh be getting into this course we won't
- at least focus on it some people may
- use this but in python you can define
- things
- uh you know separately you can have a
- separate python file where you define
- some functions
- and then you import to bring those
- functions into
- this um namespace where you can use them
- and so where you're defining the
- function where this dock string
- is in the code might be somewhere
- totally different than where you're
- actually working right now
- um but that doc string actually does
- stay attached
- to the function uh so that we can look
- it up
- so if we do the jupiter shortcut of you
- know the question mark
- after the name of the function you can
- see it actually shows
- that same doc string that we defined
- over here
- and that's going to hold true even if
- this is defined in some totally
- different spot
- and so it's useful that that will stay
- with the function
- and that will also come up if you do the
- parentheses and then shift tab
- you'll also see the description of what
- that does
- so i mean even if you're all just in one
- jupiter notebook for your model
- um it's still useful to have that right
- because your functions may be defined
- like way up at the top of the model and
- then you're using it down at the bottom
- and you're like wait what did this
- function do
- well just shift tab and then you've got
- your own description
- of what that function does and the
- arguments the inputs that it takes what
- it's supposed to output
- and so that can be really useful for uh
- keeping yourself organized and not
- having to go wait what does that do
- let me scroll up and read that code
- again i have a description of what it
- does so i don't need to do that
- and then coming to the
- default arguments in functions default
- inputs um so that's when
- you put equals something after
- the input in the definition of the
- function
- um so here this function is about
- getting the beginning of a string
- it's going to get the first however many
- characters
- of the string and
- we're defaulting the number of
- characters to five
- so um you know whatever
- we uh pass here as the string it's going
- to be
- looking for the beginning of that string
- and then
- by default it's going to grab five
- characters so my space
- st and that's why we get that as a
- result
- but we don't have to leave it at that
- default argument we can pass a different
- value for that here we want to get six
- characters
- and so now it's going to add one
- additional character onto that
- so default arguments default inputs are
- really useful
- to make your function easier to use if
- it's something where you can think of a
- reasonable default
- um then it's useful to put one so that
- you don't necessarily
- have to add it when you call the
- function but you still retain the full
- flexibility and that you can
- pass whatever you want for that argument
- so it's nice you know for example when
- you create the function which just runs
- your entire model
- that it's going to already have as
- defaults all the just like baseline
- values of all your inputs
- and then you can just pass the inputs
- that you want to change
- and not have to pass every input every
- single time
- so that um you know covers the basics of
- functions and pythons and how we can use
- them
- to group logic into units and then reuse
- those units uh in a larger structure
- and then next time we're going to come
- back to discuss python basic data types
- and you know kind of what data types are
- out there and how we can
- work with them so thanks for listening
- and see you next time
Python Basic Data Types¶
Notes¶
Everything in Python is an object and every object has a type. The type defines the data structure and functions for that object
A class defines a type (see next section)
Strings are used to represent text and have a lot of convenience functions attached to them.
We can make a “format” or “f” string by putting f in front of it. This allows us to place variables in the string and apply formatting to them.
Most of the time you don’t need to care whether a number is an integer (int) or floating point number (float). Probably the only place we will care about it in this class is looping a number of times requires an integer.
range allows us to loop a certain number of times
tuple: think list that you cannot change after creating. Better to use these when you know the objects you want in the group at the outset and you know they will not change.
Dictionaries associate one object (value) with another object (key) and allow you to look up the value by the key
Because everything in Python is an object, you can have any arbitrary nesting of objects. Lists of lists of strings, dictionaries where keys are integers and values are lists of strings, and so on, whatever is appropriate to solve your problem
The lab exercises test working with tuples, dicts, and nested data structures
Transcript¶
- hey everyone
- nick dear brotis here teaching you
- financial modeling and today
- we're going to talk about basic data
- types in python
- as part of our segment on going beyond
- an initial python script
- how we can learn the python basic tools
- and skills so that we can go
- and build financial models using python
- so we've talked a little bit about data
- types
- kind of informally so far
- we've talked about a few different data
- types already
- we have learned about strings we've
- learned about numbers
- lists and booleans so far
- [Music]
- and everything in python
- is an object and every object has
- a type um so this type defines
- uh the data structure or
- whatever object this is as well as
- any functions uh which are attached to
- that
- object and when a function is attached
- to an object
- in python we call that a method but
- still you know basically
- just a function attached to an object
- um so in order to
- define how type
- uh you know what what functions are on
- the type what is the data structure for
- the type
- in order to define that we use a class
- and that's going to be
- the next video is focusing on classes
- and and how
- we can define custom types in python
- but for the purposes of this video we're
- just going to focus on
- the basic data types that are built into
- python and how we can work with them
- so um you know we already know about
- strings we've already used strings
- you know they represent text characters
- [Music]
- and now let's learn a little bit more
- about things that we can
- do with those strings so
- you might have noticed if you do some
- calculation
- uh you end up with a number there might
- be a lot of decimals
- on that number um or the idea that
- you know you can't just type a
- percentage into python right like you
- have to put it as a decimal
- but then you want to have that formatted
- as a percentage when you display it
- and all sorts of other formats
- these formatted uh strings are going to
- be useful to help us out with that
- um and also you know it can be including
- whatever your result is as part of a
- sentence
- you know mary has five years till
- retirement
- versus just putting the number five out
- there
- so the formatted strings also help with
- that
- and so these formatted or f strings
- is the same way that you define a string
- but then you just put this
- f on the beginning of it and that makes
- it into an s string or a format string
- and that
- gives it this extra functionality that
- we can
- just drop other variables or expressions
- into the string
- and also uh tell it how that we want
- those
- formatted in the ultimate output
- so here's a little example of that so
- first doing a short calculation here
- just doing five divided by six
- and then if you just print that you just
- show that result
- uh we're looking at point eight three
- three three three three
- uh you know repeating um and so
- obviously the output of that
- does not look great right we probably
- want to round that
- if we're going to display that to the
- consumer of our model
- and then also you know what is this
- number what is the context for that
- number
- it's definitely really helpful to
- include that in a sentence
- when we display it or some other kind of
- way to tell the person who's reading
- your model
- what that number actually means and here
- you know
- we're just saying my number is because
- you know it's just an example
- calculation but
- in reality you would want to actually
- describe what that number is
- um so you see the result of
- using this f string is ultimately we get
- this kind of
- output my number is 0.83 and now it does
- not have
- all these decimals on it we can see it
- only has two
- decimal places so we can break down how
- we did this
- so you'll notice uh with this f string
- uh
- you see we have we have that f and then
- the quotes so that's how we know it's a
- formatted or an f string and that means
- that
- we can do this it's not just a normal
- plane string
- um and then we have my number is you
- know just like we're going to see in the
- output
- and then here comes the special part so
- here we have
- um the curly braces
- and within the curly braces that's where
- we can do
- this variable substitution or expression
- substitution
- uh in order to drop our numbers into the
- middle of a string
- so whenever you do the curly braces
- that's going to say
- here is where i want to put whatever
- variable or expression
- you know you could even do simple math
- inside of here or whatever
- uh call a function or whatever you want
- to do valid but
- as long as it's valid python for the
- most part it should work in here
- um and then inside those curly braces is
- where we put
- you know what we actually want to put
- into the string
- and you'll notice you know here as well
- as you know jupiter and
- any other editor is going to help you
- out here
- and you notice that uh this changed
- color versus the rest of the string
- right the rest of the string is red
- signifying that it's just a string but
- then this part
- went black signifying that it's now
- looking at the variable mynum and not
- just a string
- mynum so we're going to take this value
- and we're putting it here in this point
- in the string so
- you know if without this extra part we
- would get my number is
- zero point eight three three three three
- through three uh and so on
- if you just did curly braces my num
- curly braces
- that's without doing any kind of
- formatting to it just put it in there
- exactly like it would print normally uh
- but then we also want to apply
- formatting to it
- so to apply formatting to it then we
- have this
- colon and then after the colon we
- specify
- a format code um which says
- you know how do we want to format this
- number uh so what this one
- here means is we want to have a decimal
- format we want to have two decimal
- places and we want that to be a fixed
- number of decimal places uh so even if
- you put like five
- just plain five in here it would come as
- five point zero zero
- because we have two fixed decimal places
- [Music]
- and there's a lot of different codes
- that you have there you know it goes
- beyond just
- basic numbers you can also have things
- like formatting a date
- or other things um and
- i have included in the resources a
- reference that you can look at
- uh for all the possible format codes but
- for the most part
- uh you know we're gonna use like this
- fixed uh
- you know just number of decimals or
- we're going to format it as a percentage
- those are going to be the main
- uh ways that we're going to use these as
- far as this class
- and when we jump into the jupiter
- example we'll look at a few other
- things that we can do with strings as
- well
- then jumping back over to numbers in
- python so we've already talked about
- numbers in python we've already used
- numbers in python
- um but you know i've been saying that
- numbers are type
- in python but that's actually a bit of a
- simplification
- uh there are actually two main types of
- numbers
- in python a floating point number and an
- integer
- or float and end would be these two
- main data types for numbers
- and the vast majority of the time you
- don't have to care
- whether it's a floating point number or
- an integer
- it really does not matter most the time
- and that's why i've
- you know just kind of simplified it so
- far
- but occasionally it does come up and so
- it's important to
- know about it still um and so the
- difference here
- is that you know an integer you know
- just like going back to
- you know plain old number theory an
- integer is you know a whole number
- uh you know one two three negative one
- two three
- zero uh it doesn't have any decimals
- whereas a floating point number does
- have decimals
- so even if it's zero
- even if all the decimals are zero if it
- has decimals
- it becomes a floating point number
- so that's why if you look at a couple
- examples here
- so 3.5 that's a floating point number a
- float
- 3.0 you might think that's an integer
- but actually it's a float as well
- because we did point zero
- uh even though you know that's three
- it's the exact same value as the integer
- because we did that point zero that
- makes it actually change the data type
- to a floating point number rather than
- the integer
- it's only if we just put the integer
- part of it just a 3
- then it becomes an integer
- so uh and you know you can compare
- across
- uh floats and then just fine you know if
- we do 3.0
- is that equal to three that'll return
- true those are definitely equal
- and yet they have different data types
- um and so again most the time this
- doesn't matter
- but one instance where we are going to
- run in that it does matter
- is if you want to loop a certain number
- of times
- and we'll look at that in the jupiter
- example how we do that say we just want
- to loop five times
- uh you cannot give it a float you can
- only give it
- an integer uh because you know looping
- 5.6 times
- doesn't mean anything right like what do
- you do for that point six
- loop um and so python has restricted it
- so that it only will take an integer
- because those would be the
- sensical values for that um so if you
- try to pass it
- afloat then you'll get an error
- about that and we'll see an example of
- that in the jupiter notebook
- and then we'll just introduce a couple
- additional built-in types
- and these are both like container types
- they hold other
- objects so one here is a tuple
- and a tuple you can think of as it's
- basically a list
- uh you know it holds items they're
- ordered you can look them up by index
- but the one main difference between a
- tuple and a list
- is that uh you know with the list you
- can create it with ever
- with whatever items and then you can add
- items you can remove items
- uh whereas the tuple cannot be changed
- after
- it's created whatever you have in there
- when you create it
- is going to be what's always in that
- tuple you cannot append
- you cannot insert you cannot remove
- and so it's always what you started with
- um and the difference in specifying it
- is that you're going to use parentheses
- instead of square brackets um so this
- here would be a tuple of a and b
- and you know generally you're just going
- to want to use tuples
- if it's some instance where you don't
- need to change the items
- and if it is some instance where you are
- going to need to change it
- as you go through your code then you
- want to use a list
- instead so you know not a not a huge
- difference
- but it's definitely a nice little extra
- protection that if you're
- expecting that this um you know it
- shouldn't change
- at all uh if you use a list for that you
- could accidentally append to it or
- remove from it and that could mess up
- all your other code
- so it's just a little bit safer to use
- tuples and they are more
- performant as well
- then the other data type that we're
- introducing here
- is a dictionary or dict
- and so that is a mapping of values to
- other
- values so you know you could
- map a to one and then you can go back to
- this dictionary and look up
- what's the value for a and you're going
- to get one
- is the basic idea behind them um
- and we're not going to use them
- immediately other than just you know
- introducing them and playing around with
- them understanding how to use them
- um but we will definitely use them as we
- proceed throughout the course
- so i wanted to introduce them now since
- they are a very fundamental data type
- in python
- so with that we can jump over to the
- jupiter example
- so uh first going back to strings
- here um so again uh
- you know you define it with quotes then
- you're going to get a string
- right so we have that string
- abc uh and we have the type of that
- being
- a string um and
- one thing which we haven't mentioned
- before is you do have an option
- of whether you want to use single quotes
- as i have been using
- or you can use double quotes for that as
- well
- it does the same thing and so it doesn't
- really matter
- which one you use now you don't want to
- mix them you don't want to do a single
- quote and then a double quote
- that is going to give you a syntax error
- so watch for that
- you know typically just pick one style
- and and stick with it
- it really doesn't matter too much the
- only time that
- i ever make a conscious decision of
- which one i'm going to use
- is if i want to use the other
- mark inside the string right so here i
- wanted to use
- a single uh quote inside the string and
- so i use double quotes on the outside
- if i use single quotes on the outside
- for that
- then i mean you can see already that
- it's messed up just looking at the
- coloring here
- and again we're going to get a syntax
- error because it interprets the string
- ending here
- and then from here it starts to
- interpret these as just variables and
- and yeah it can't uh this is not valid
- python at this point
- um you can work with that by putting a
- backslash there
- that escapes the uh
- the quote and then we're back to uh what
- we have before
- um but i think it's you know if you know
- you're going to use a single quote
- then just put double quotes on the
- outside that's a little bit clearer
- and then if you know you're going to
- have to use double quotes
- then again you would want single quotes
- on the outside to
- make sure that you don't have any issues
- there
- but beyond that it really does not
- matter just pick one
- and stick with it consistently make sure
- that you have the same
- character on both sides of the string
- for it to be valid
- so there's a lot that we can do with
- strings
- and so if you want to look at
- you know all the things that you can do
- um
- then you just can you know do dot
- after the string and then hit tab and
- then
- jupiter is gonna pop up all the possible
- things
- that you can do here um so there's tons
- here
- and we're not going to use the vast
- majority of it in the course
- but it's all there you know basically if
- you think
- uh how do i capitalize a string
- well you can you know just just scroll
- through these and look for what
- you know makes sense oh a dot
- capitalized yeah that sounds right
- um now i can see that it got capitalized
- at the beginning
- um but what if uh you know
- i don't know i want to get it to all
- uppercase and i don't know
- uh you know again i could look through
- the methods and try and pick it out
- um but definitely you know google is
- your friend
- uh python string uh
- to all uppercase are all caps let's do
- that
- um so then um
- we can see some results coming up oh
- string dot
- upper maybe that's uh what we need
- oh string dot upper okay that's what we
- can do
- um so then we put upper there instead
- and we can see that does indeed work
- so definitely google is your friend for
- finding out what you can do in python
- there are so many resources out there
- there are millions and millions of
- people out there who work with python
- and so it's really easy to find help uh
- for you know how do i do this particular
- thing just google it
- you're most likely going to find some
- kind of answer
- um and then don't really worry about
- this code this was just so that
- in the notebook i could have printed out
- all these different methods that we have
- on the string
- and then you know here my a
- is all lowercase so you know is lower i
- can check if it's all lowercase so you
- know these are just more examples of
- things you can do with the strings
- but there's so many things here and you
- can just google for whenever you need to
- do anything
- in particular
- so moving on to numbers um
- so again it's not just numbers we have
- floats and ants in python so 3.5 is a
- float
- 3.0 is a float 3 is an n
- even though 3 is equal to 3.0
- we can see that the types themselves are
- not equal
- even though the values are equal
- so again it doesn't really matter most
- of the time whether you have floats or
- integers you know you can go and you can
- do math
- uh you know with with one being a float
- and one being the integer
- it doesn't matter um
- where it does matter is when we want to
- loop a certain number of times
- um and there are other places as well
- but you know probably
- they're we're not really going to hit
- them in the course this is the one that
- i know is going to come up in the course
- um so here is a basic way that we can do
- a loop
- for a number of times this is the
- built-in function range
- you give a range a number
- and it's basically like making a list
- in the background of all the numbers
- leading up to that point
- um not exactly it's not actually a list
- it's a generator but we don't need to
- worry about that we can think of it as a
- list
- uh and effectively for our purposes it
- works uh
- like creating a list with um here it
- would be
- zero one two three four um so again that
- um zero based indexing um
- it's gonna start from zero on the first
- one and it's going to reach
- ultimately the fifth number which is
- four
- um so then if we do want to get you know
- starting from
- one instead you can either you know just
- add one
- to the number you know here is also
- showing that we can put an actual
- expression
- inside one of these f strings it doesn't
- just have to be a variable
- we also don't need to have the format
- part we can have just
- the uh the value itself here the value
- didn't need formatting and so
- we left it off um
- and so you can do it that way
- or you can
- instead you know start the range from
- one and then go to
- one higher than where you actually want
- to go that will also
- uh get you the one based indexing there
- um but anyway so that's you know how you
- can run a loop for a certain number of
- times
- but you know let's say that we
- um you know we had uh
- let's see you know num loops um
- equals 10 divided by two um and so okay
- yeah that should be five
- loops right um and then we put that
- there
- um we're gonna get this float object
- cannot be interpreted as an integer
- because this num num loops
- came as a float any result of division
- is going to be a float
- and so this is not going to work you
- need to pass an integer here
- even though uh you know the value of
- that
- is five and we check
- is it equal to five yeah why doesn't
- this work right but it's because it's
- not
- an integer so
- there is a very easy way to fix this
- if you take this you know we have this
- num loops which is a float but if we uh
- take the integer of num loops
- then that will get us back to having an
- integer
- so we just wrap it in int and then we're
- going to have
- an integer come out of that you do need
- to be careful with that because that
- will kind of do the floor
- if you do n of 5.6 that's gonna give you
- five right you are losing information
- there
- so you want to make sure to only do that
- if you know that it's a whole number
- anyway or you don't care about this part
- of the number
- um but it is a solution for this because
- we know this is going to be a whole
- number
- it's just coming as a float we just put
- this
- in an n as well and now all of a sudden
- this works just fine
- so that's uh the additional material on
- numbers and now let's look at
- tuples so again tuples you know work a
- lot like lists
- you can index them you can loop through
- them just like lists
- but you just can't add or remove items
- so here i'm going to define
- my tube as one two three uh so we have
- these three numbers into this tuple
- um that's one way you can create a tuple
- another way
- is you know if you already had a list
- you can convert that list into a tuple
- so here i have a list abc and now i'm
- doing
- tuple of my list so here another
- built-in function
- tuple um
- and that's converting that list into a
- tuple now
- now that list still exists you already
- defined it it's still there
- but you just now also have this tuple
- separately which you're not going to be
- able to add or remove items
- and then you know the same thing works
- for converting from tuples into lists
- uh if you wrap you know whatever in list
- then it's going to convert it to a list
- so here we went from a list to a tuple
- and back
- to a list you know really just for sake
- of example here
- you wouldn't normally just be going back
- and forth for no reason
- but um just showing that you can easily
- convert back and forth between lists and
- tuples
- um now we know that um
- you know we define lists like uh we can
- do a
- equals you know five six seven or
- whatever
- and then that's you know gonna give us
- five six seven also
- uh if you just have that five in there
- then that also
- works just fine uh the type of that
- is still going to be a list but you do
- need to be careful with tuples
- uh when you create a tuple um you know
- also
- if you have multiple items you don't
- really have to think about it it'll work
- fine
- the issue is creating a tuple with a
- single item in it
- uh because if uh you want to create a
- tuple with a single item you
- do have to put a trailing comma on it
- so that python knows that it's a tuple
- so this here is going to create a tuple
- um whereas this here is not going to
- create a tuple
- even though you think you know i put the
- parentheses it should be a tuple
- uh if there's only a single item you do
- need that trailing comma
- so you can see actually it's not coming
- as the tuple of a anymore it's coming as
- just a
- and it's coming as just a string and
- that's because
- you know tuples are not the only meaning
- of parentheses in python
- parentheses and python can also be used
- to group things
- for you know like order of operations
- purposes
- um so here we basically made a group
- which has just a in it
- which just then again evaluates to a um
- instead of uh what we intended to do
- which was make a tuple
- there you do need the comma to say that
- it's tuple
- um but you know just like lists you can
- index them
- so my second tuple again was abc
- um so you know zero is going to give us
- the first item
- up until a negative one gives us
- everyone with the last item so the
- indexing
- all works exactly the same as it does
- for lists
- um you can also uh loop through them
- just like um just like this
- um so that works just fine
- um the one thing that you can't do
- is you can't go and try uh and append to
- it
- um so let's try and append 10 oh wait
- super object has no attribute append
- right because you can't add
- anything to an existing tuple
- so that's tuples and then the other
- totally new data type we're looking at
- here
- is uh dictionary so dictionaries i mean
- it's going to be you know dict is
- is how it's you know talked about in
- python
- so that's a mapping of items to other
- items objects
- other objects and so you know here's an
- example
- and you can define the dictionary with
- these curly braces
- so what this is saying is we have a
- dictionary
- and we have uh the key a
- mapped to the value one and we have the
- key b
- mapped to the value two so it's whatever
- you know two things you wanna associate
- with each other you put the key first so
- the key
- is what we're gonna be able to look
- things up by
- and then you put a colon and then you
- put
- what you want the value or what is the
- result
- of looking up by the key so
- let's make that a little bit more
- concrete so i've got my dictionary here
- a is associated with one b is associated
- with two
- that means we can go and we can look up
- the value
- for a and here you know we say give me
- the value
- for a out of my dictionary and we get 1
- because 1
- was associated with a similarly we can
- look up b
- and it's going to give us the value 2
- because that was the value associated
- with b
- and if you try to look up a key which is
- not there
- then you're going to get a key error
- because it cannot find that key
- in the dictionary
- and also you cannot look up by the value
- you cannot look up one and expect
- to get a uh you know there is there are
- definitely ways to reverse the
- dictionary and
- and make it look up the opposite way but
- you know just basic usage
- you look up by the keys and you get the
- values as a result look up by
- a and b get one and two not the other
- way around
- um so we'll definitely do a fair amount
- more with dictionaries as we go through
- the course
- but i just wanted to kind of introduce
- them very quickly here
- just so you're familiar with the idea of
- them and we'll build on that more
- later
- uh so the last uh topic that i want to
- talk about within
- the basic data types is this concept
- that um again everything in python is an
- object
- and so everything is kind of treated in
- the same way and that
- allows you to have any kind of nesting
- of data types that you want you can have
- very
- you know complex nested data structures
- just based out of these basic data
- so for an example a very common
- one of these types of data structures is
- to have a list
- of dictionaries so then
- you know each dictionary is representing
- like some kind of entity
- here each dictionary is representing
- a person and we have multiple people
- so each dictionary is one person
- and then we have multiple people in the
- inputs list um and then within the
- dictionary we have
- you know some different characteristics
- of this person
- so uh name and weight are the two
- characteristics that we're tracking here
- um and so for john we have his name is
- john of course
- and then that his weight is 180 and for
- the other one the name is sarah and the
- weights 140.
- um so then you can do something like
- uh you know loop through this inputs
- list so that
- this input variable that we're getting
- here is the entire dictionary itself
- and then we want to pull the name out of
- the dictionary and the weight
- out of the dictionary to display details
- about each of these people
- so then you know this is each of these
- people introducing
- themselves for whatever reason they
- introduce themselves by saying their
- weight
- but uh you know the basic idea here is
- you can work with the any kind of nested
- data structure
- and uh you can take this to any level
- that you want
- so here's a more complicated example
- um so again each it's a list of
- dictionaries where each dictionary
- represents a person uh but now also
- each person has friends associated with
- them and so then friends
- is itself a list of
- dictionaries which again represent more
- people
- and then for each of those people it
- says the activities that they have
- shared
- with the original uh outer person here
- so definitely a more complicated data
- structure to work with here
- but you know the idea that you can
- continue to nest these things as many
- times as you want for whatever
- data structure makes sense for the
- particular problem that you're working
- on
- um so here's you know
- for the point that we're at uh in our
- python learning this is kind of a lot
- going on here
- um i don't expect you to understand uh
- this whole
- block of code right now if you if you
- take the time and really go through it
- um you can definitely
- figure it out um but mainly here i'm
- just trying to highlight
- uh that you can work with these nested
- data structures um
- and so here i'm ultimately uh printing
- you know for each person
- you know who who they hang out with and
- what they do together
- um and so you know sarah here has two
- friends and we see
- two statements for sarah um and then i
- made it also
- uh you know if it's not the first person
- that it's gonna say they also
- hang out with um so
- yeah you can you know have any kind of
- arbitrary logic that works with any kind
- of data structure
- things are very flexible in that sense
- in python
- so that finishes up the material for the
- basic data types
- in python next time we're going to talk
- about creating our own
- custom data types by using python
- classes so thanks for listening and see
- you next time
Creating Python Data Types with Classes¶
Notes¶
We’ve talked about strings, floats, ints, lists, tuples, and dicts as basic data types. It is possible to define your own custom data types as well using classes
I will not be expecting you to construct your own data types in this class. This section is mainly so you can understand how Python works in general. We will start using custom data types defined in external packages so it is good to have an understanding of this and how to use custom objects.
The difference between objects of the same data type (same class definition) is the data contained within. They will all have the same functions attached to them (called methods when it is functions attached to objects)
Feel free to study the car example in more detail to get a greater understanding of how to define classes, but we will not spend time on this
Dataclasses are simplified versions of classes meant to group data together. We will use them to organize our model inputs.
The lab exercises test working with externally-defined custom data types and creating and using dataclasses for our model inputs.
Resources¶
Transcript¶
- hey everyone
- nick dearborn is here teaching you
- financial modeling and today we're going
- to talk about
- creating data types in python with
- classes so this is part of our segment
- on going beyond an initial python script
- the tools and skills that we need to get
- to
- building financial models in python
- so we have already talked about
- data types and the basic data types that
- are built
- into python such as strings uh you know
- floats
- in tuples dicks booleans
- etc but i've also mentioned
- that we can also have custom data types
- in python
- and that is where uh you know the
- flexibility
- of python really comes in
- and that you can do basically anything
- with python and you can build all these
- sorts of extensions to python and
- people have you know put out 250 000
- different packages
- out there which extend python
- functionality
- and most of that is by way of defining
- these classes to create
- new data types that you can use when
- you're working with python
- so um
- the class is the definition
- of the data type itself
- um so that's definitely a little bit
- abstract
- but let's break down what the data type
- actually means and it will become a
- little bit more concrete
- um so a data type and python
- is just uh a way to describe
- the data which should be stored
- within the object and the functions
- which are attached to the object and we
- call those methods
- when they're functions attached to an
- object
- and so we define the class and that
- defines the data type
- and then you can create objects of that
- class and so from a single
- class definition a single data type you
- can have as many objects
- as you want of that type
- and so for each one of those objects
- they could potentially have different
- data that you're passing in
- or that particular object but they're
- going to have
- the same functions attached to them the
- same ones which
- are defined within the class and
- attached to the data type
- and while the data itself may be
- different the structure
- of the data is going to be the same
- because that is also
- defined within the class
- so again you know everything in python
- is an object except for just you know
- the names of things
- those are just references back to those
- objects
- um and so we've already seen these
- strings floats it's list tuples
- they're just types of objects and there
- are other types other built-in types
- that we didn't talk about because
- they're not going to be
- you know very useful for the things that
- we're doing or at least uh
- you know at the level of python that
- we're going to explore in this class
- there's definitely a few that
- would be useful but are just more
- advanced to use
- but you know we're not limited to just
- using those built-in types right there
- are these custom types
- you can you know import a package which
- is going to have its own custom types
- and you can just
- use those and benefit from the
- functionality they built out
- or you can define your own class and
- associated data type
- and use it for your own model or program
- so again the class defines the type
- of the object um
- and then we can create as many objects
- as we want
- of that type
- so um
- the class definition is going to say
- what type of data we need to pass in
- to create an object of that data type
- and then we also on that class define
- the functions or methods
- which should go along with that type
- of object and then every object we
- create
- of that type is gonna have all those
- functions
- so it can be a nice way to uh organize
- your code so that it can
- easily be reused
- um so to make this a little more
- concrete
- you know thinking about the list that's
- the data type we're already familiar
- with we've already worked with
- so in the list we might have one list
- that has one two three
- another list that has abc right we
- constructed them both in the same way
- they're both expecting to receive this
- sequence of different objects
- and so uh you know the class definition
- for lists
- that's in you know python's source code
- um
- you know says that we should pass it
- some kind of sequence of items
- and that's going to become you know just
- an ordered
- uh structure in the list
- uh within every single list that we work
- with we can do it
- a dot append and that will add into the
- list
- right if that's an item in the list so
- no matter if it's the one two three list
- or if it's the abc list
- either one we can append on it just
- anything that's a list
- we can do an append on it and that's
- because that append
- is defined within the class which
- defines the list
- data type
- so then looking at that you know with
- that same kind of visualization that we
- looked at before
- where we have one class it defines the
- structure of the data and it defines the
- functions and then we can create objects
- of that
- so here list is the class
- and so for the list you know we have the
- items
- and the lists you know just this ordered
- sequence of items
- and then it has defined the methods
- append
- insert pop etc all the other uh list
- methods that we work with
- and so whether we create you know a list
- of
- a and b the strings or we create a list
- of one and two they're both gonna have
- append insert all the functions uh
- but the actual items the data is inside
- uh is gonna be different this one has a
- and b this one has one and two uh but
- they are in the same
- structure they are you know a sequence
- and ordered sequence
- of items
- um so this concept extends
- to creating your own custom data types
- so uh you know let's use a car as an
- example because that's you know it's a
- very concrete thing that everybody knows
- about
- um so we can make a class uh for a car
- and make a dab type for a car
- um and so you know for a car
- you think about kind of the main
- characteristics uh
- you know right at the highest level the
- make and the model are like the most
- important characteristics of the car
- right um
- and so you know certainly there there
- could be other characteristics
- uh other data which we have within the
- car
- um data type but let's just keep it
- simple and say you know just make and
- model
- are the two pieces of data which we're
- gonna have
- in the car and then with a car you can
- drive the car
- uh you know you can fill it up uh add
- gas to it
- etc um and
- so uh we can create then you know two
- different cars here
- we can create a honda civic bypassing it
- honda and then civic
- um and so the make is going to be honda
- the model is going to be civic
- and that you can drive the honda civic
- you can fill up the honda civic
- or we could create the toyota corolla
- and for that the data is going to be
- different though it will be in the same
- structure it is going to have a make it
- is going to have a model
- it's just going to be different values
- for each of those
- and we are going to be able to drive it
- we are going to be able to fill it up
- etc so again the functions
- come universally to all the objects and
- the data structure
- is going to come but it's going to be
- different actual values
- in the data depending on how we created
- the object
- so um let's just say we have this
- car class defined elsewhere
- so we're going to import that car
- class and so this can be as simple as
- just you know a python file
- in the same directory as your notebook
- then you would be able to import like
- this or it could be from some
- external package which you've installed
- then you can also
- import like that if this was the name of
- the package
- um but you know the main idea is we're
- just we're getting the car
- uh class even though we didn't define it
- you know
- in this particular uh session directly
- so then we can create the car and
- calling a class to create an object
- of that data type looks just like
- calling a function
- you put the name of the class and then
- open parentheses
- and then you pass whatever inputs and
- then close parentheses and that's going
- to make
- the object so if we print that out
- then we can see that it prints as a car
- and then if we check the type we can see
- that the type is
- a car type inside the
- car example module
- and then if we check the make of this
- honda civic we get honda
- and if we call the drive method uh
- then we're gonna see that it's driving
- away um
- so again you know calling any function
- we gotta do open close parenthesis to
- actually call
- that function in this case a method
- so you know it's generally a little bit
- more advanced
- to construct your own classes your own
- custom data types
- that's not where we're going to be
- focusing in this course
- i would definitely encourage you to
- learn about that it's very useful
- you know i certainly apply it all the
- time
- but it's just you know one of those
- things where if this was a two-semester
- course i would be happy to spend time on
- this
- but we have very limited time we got to
- make sure to
- get all the financial modeling material
- in and so we can't spend a bunch of time
- on
- you know more generally useful
- programming concepts
- so definitely i would encourage you to
- learn about that on your own
- you will definitely find it useful going
- forward
- but for the purposes of this course you
- don't need to know how to do that
- um now why do we just cover this
- if we're not going to go and create our
- own custom classes
- so couple reasons one is just to give a
- better understanding of the general
- workings of python you know again
- everything
- in python is an object every object has
- a type
- we can define those types using classes
- and then you know when you're just
- calling functions or methods
- um you know sometimes we've had like
- you know when it's a list we do dot
- append and so it's you know
- attached to the object we then do a dot
- and then we call a function versus if we
- just define a function
- then you're just calling that open close
- parenthesis there's not a dot or any
- variable before that
- so hopefully this makes a little more
- sense now
- that when we see this kind of format is
- because
- uh whatever the data type of the object
- the class has defined this function as a
- method
- of the data type and so you can do dot
- and then the function on anything
- of that data type versus a plane
- function
- is not attached to any data type and you
- just call it
- uh by its name without any dot or
- variable name before that
- and then the um
- you know one other reason which i didn't
- put on here is then that
- uh you know all these uh libraries which
- are going to bring in
- and work with they have defined their
- own
- custom classes and so just getting a
- little bit more visibility
- into you know when you just import car
- and you use that like what is going on
- where did that come from what is this
- car thing
- it's a class and that defines the data
- type that we're going to use
- so you know giving more visibility into
- how that works
- um but then also there is a
- simplified version of classes called
- data classes
- and we are going to directly create
- those
- so those we're going to use to organize
- the inputs
- for our model um
- but we're not going to go to building
- you know full-on just general classes in
- this course you can certainly feel free
- to use them
- in your projects if you you know figure
- out everything on your own
- i'm happy to answer questions on them
- but it's just not something we're going
- to
- focus on in the course um
- but data classes we will so data classes
- uh is they're a lot simpler to define
- than a class um and typically they're
- just used to kind of group data together
- which is exactly
- what we're trying to do here
- so for data classes here's kind of the
- setup
- to define a data class
- so here um we do need to import it
- it is built into python but it's uh
- you know there are about 30 or 40
- modules
- or packages which are built into python
- but you still need to import them
- they're not just you know they're
- waiting for you to use it you still need
- to import it even though it comes with
- every python
- this is one of those instances data
- classes is built in
- but we still got to import it so we do
- this import so we get the data class
- and then um this is what's called a
- decorator
- you don't really need to worry about
- that that's definitely a more advanced
- uh concept actually you know like
- creating decorators and understanding
- how they work in detail uh we're not
- gonna go there
- in this class that's definitely
- something you can learn about on your
- own
- just know that you have to put this at
- data class at sign data class
- above the class statement and then it's
- class
- the keyword class and then whatever you
- want the name
- of the class to be and then a colon and
- then just like we've seen with
- you know if statements we've seen it
- with for loops we've seen it with
- defining functions
- we do this colon and then after that we
- have indentation and then everything
- indented
- is going to be part of this class
- definition
- so for that the data class
- uh what we do is we define all the
- pieces of data
- which are going to be stored within this
- class so we're defining that data
- structure
- of the class and so here
- i'm going to say that these model inputs
- should have interest rates as one of the
- pieces of data in here
- and that should be a tuple and that's
- going to default to five six and seven
- percent
- and then uh we should have a payment
- as well that's going to be a floating
- point number
- um because it could have decimals
- potentially
- and we're going to set that equal to a
- thousand by default
- um so then we can create
- an instance of the inputs so again it's
- just like the functions you know first
- you have to define the function and then
- you have to use the function
- same concept with classes first you have
- to define the class
- then you can use the class so
- here we're just setting up the
- definition uh
- you know this we're setting up this part
- we haven't actually created the objects
- out of it yet
- so to create the objects then it looks
- again just like calling a function
- you put the name of the class and then
- open parentheses
- and then you pass whatever arguments and
- then you close
- the parentheses so here
- we're passing that the payment uh should
- be equal to
- 2000 um and we're not passing the
- interest rates
- so those are gonna take the default
- value of five six
- and seven percent so then when we print
- out
- the inputs then uh we're going to see
- that it's an instance of
- model inputs um we have the interest
- rates five six and seven percent
- and we have a two thousand payment here
- and the type of that
- is model inputs and we can grab those
- individual things
- out of the inputs we can do inputs dot
- interest rates
- that gives us five six seven percent and
- we can do inputs.payment and that will
- give us 2 000.
- so that's the basic idea of how to
- create and work with
- data classes so why
- why would we want to use data classes
- when are we going to use data classes
- so again it's just a convenient way to
- group data together you can definitely
- use them for a lot more than that
- but that's the most common usage and
- what we're going to be focusing on in
- this course we just have
- you know all these different inputs we
- just want to package up those inputs
- into a single place
- and you know the reason that we end up
- going to this is because financial
- models
- uh typically have a lot of different
- inputs you know we might have easily
- you know 15 20 30 different inputs that
- we need to pass
- in and uh you know what you'll find when
- we go with this structure of having you
- know functions within functions
- and passing the data you know back and
- forth between all the functions
- if you keep everything as just
- individual variables
- all of a sudden you know every function
- is passing like 10 inputs to each other
- function
- and it just becomes very tedious to be
- passing
- all these individual variables around
- everywhere so by grouping it all into
- a single data class we can just pass
- this data class
- around we can pass the instance uh of
- the data class around
- as one single variable and then we have
- access to all the inputs in every
- function
- very easily just by passing this data
- so it's mainly a convenience thing it's
- also going to make your code shorter
- and that it groups all your inputs
- together
- um
- the other nice advantage of this was um
- again all this data is together and you
- can just
- you know whatever the name of your
- instance is for the data class
- you type that and then you do dot and
- then you hit tab and you're gonna see
- all your inputs right you can auto
- complete all your different inputs
- you have just your inputs there you
- don't have all your other intermediate
- variables and things like that
- um so it's it's nice and convenient to
- work with it as well even within
- the functions
- so let's go ahead and look at the
- jupiter example for this
- so um again every data type
- has an associated class um so even
- the built-in data types they also have
- classes um and
- so um those built-in data types often
- have
- also more convenient ways to create them
- but you can create them just like a
- normal class as well
- um so you know for strings we've looked
- at creating them like this right like
- singular double quotes
- automatically is going to go to a string
- that's a little just
- you know shortcut python has thrown in
- there for us to make our lives easier
- because we use strings all the time
- um but uh you know scr
- is actually the class uh for
- string the name of the class for string
- i mean you can see that when you check
- the type it's str
- um and so you can also create strings
- by you know just like we looked at with
- car and with model inputs you put the
- name of the class
- and then parentheses and the data you
- want to pass and then close parentheses
- that's going to work exactly the same
- way so this would be
- you know kind of just the standard way
- of using any class
- here we're using it for the string but
- of course you know the built-in data
- types have the more convenient ways to
- construct them as well
- uh but then moving to custom classes um
- so you know here we're gonna look at
- working with this custom car
- class and if you're curious uh you know
- what this code looks like to create this
- class
- uh we have it here in this car
- example.py
- um so it's all this stuff here
- and you know this stuff is probably not
- gonna make a lot of sense
- uh just looking at it um there's you
- know a fair number of things in here
- which
- uh takes some deeper knowledge of python
- to understand what's going on
- um so don't really worry about it uh you
- know if you have extra time
- i would recommend reading out more on
- classes and learning about how this
- works
- but it's not going to be anything that
- is covered in the course
- so we don't really need to worry about
- how it's actually defined
- we just want to work with it right
- so um here i'm doing from car example
- import car and this worked because
- i have car example defined in the same
- folder
- as my notebook so if you want to run
- this on your own make sure you download
- this car example and that it's in the
- same
- folder as your notebook in order for
- this to run otherwise you're going to
- get an import error
- it won't be able to find car example
- and you won't be able to run this part
- of the code
- so um here we're going to make a
- subaru forester that's going to be my
- car
- and we can see it's coming through as a
- car with the make
- as subaru and the model as forester
- and so now you know we have these
- methods which are attached
- on the data type the class of the car
- and if we hit dot and then tab we can
- see what those are
- and jupiter even helps us out a little
- bit here
- um with telling us you know what is this
- thing these two are functions right
- drive and fill up whereas the gas
- percentage the make and the model those
- are data and stored within the class
- um so checking you know make i'm going
- to get subaru
- or you know running drive i'm going to
- see that it's driving away
- and that the gas is now down to 40
- percent
- so if i you know keep driving the car
- here i'm going to drive it five times
- um we can see that it drives and it
- takes 10 of the gas to drive and then it
- drives and takes 10
- more and so on until we hit zero percent
- um and now we are out of gas
- um so now when we
- um call drive we are just going to be
- out of gas no matter
- how many times that we drive um
- so that's the basic you know idea here
- and then we can
- uh you know fill up the car now the gas
- is at 100
- and we can start you know driving again
- until we get down to
- zero percent um then it's out of gas
- and then we can fill it up etc so you
- can give whatever kind of functionality
- you want to your objects
- and uh you know we're going to show or
- we're going to use
- these custom data types defined in other
- libraries
- uh that help us do a lot of interesting
- things uh
- without really understanding you know
- how that was defined
- in the background we just need to know
- you know how can we
- figure out the functions on this um how
- can we
- uh figure out the data associated with
- this and you know just doing the dot tab
- is going to get you a lot of the way
- there and then you know the other main
- part of it
- is you can also just google about
- whatever
- um you know custom data type that you're
- working with you know here
- i defined this car so you're not gonna
- find that on google
- uh but uh you know for any of these
- libraries
- packages that we're going to work with
- you'll be able to google
- all about it
- so then that brings us to data classes
- where data classes are
- the simplified class so you know we had
- a lot of stuff
- going on here in this class um
- but for the data class i mean bam we got
- four lines
- and it's done right it's a lot simpler
- to define that
- um so we got to have this data class
- import
- and then we've got to do this at sign
- data class
- this decorator um you know again you
- don't have to worry about what a
- decorator is
- that's a more advanced python thing but
- you just know that you put it here
- for a data class and then the very next
- line you want to have as the class
- statement
- and then you have the keyword class and
- then the name
- of the class you want to create and then
- a colon and then the indent and then
- this is where you start defining
- your variables uh that are going to be
- attached to
- the class um so again this is just
- like the um
- example in the slides we have a payment
- defaults to a thousand and we have
- interest rates defaults to five
- six and seven percent
- um so then you know again
- this is just the definition part right
- we haven't actually uh
- created any concrete object we haven't
- you know we don't have this data really
- anywhere yet
- uh we need to create an instance of the
- class uh to get that so here we're doing
- data
- data equals model inputs open close
- parentheses
- so again you know just like functions to
- could to create an instance of the class
- you put the class name
- and then open close parenthesis and you
- can pass any arguments
- in here um so you know i could pass 2
- 000 and that would come
- for the payment um you know 2 000
- then i could do you know 0.1.2.3 if i
- wanted to change the interest rates as
- well
- also uh if you want to
- change you know them not in order then
- you can specify them by name
- now it's taking the default payment of
- thousand and changing the interest rates
- um
- but you can also just do it with nothing
- to get the defaults for everything
- and then once you have that um well we
- can just do data dot
- and look at it well we've got interest
- rates and payments
- are the two pieces of information we
- have associated with that data class
- so we can you know look up either of
- those individually
- and get that value back
- so here's showing also that you can
- override those defaults
- and get that information as well
- so then to show the motivation why we
- want to use these things
- rather than just passing around the
- payment interest rates themselves
- uh so here uh we have a function
- which is going to determine
- uh you know if you have an interest rate
- and you have a payment
- what would be the principal that uh
- you know got to that percentage interest
- rate equating that payment
- um and then uh you know does that for
- each one of the interest rates
- so we can call that um and
- we uh call that and we get
- the results we would expect you know for
- three percent uh
- to get to a thousand payment that would
- have had to have been thirty three
- 000 principal and if it's a four percent
- interest rate to get to a thousand
- dollars it would have had to have been
- 25 000
- um so but you did notice
- um that we had to pass the payment and
- rates
- separately here um where as
- if we create a data class um
- here we're creating the data an instance
- of model inputs
- and then here we pass only the data and
- in here then we do data.interest rates
- data.payment
- um to get the same result um so the key
- difference here being
- two things one is that we passed only a
- single
- argument here and the other is you know
- while you're writing this
- you can go you know what were my
- variables data.oh it's interest rates
- and then use that what was the other one
- oh it's data.payment
- um so
- um you know not a big difference when we
- only have two inputs
- but you can imagine if you had 10
- different inputs into
- you know the function that runs your
- whole model um
- then all of a sudden we're passing a
- whole bunch of things here and it gets
- pretty tedious just typing out all those
- separate variables each time
- it might be that then your main model
- function which takes these ten inputs
- then passes
- five of them to the first sub model and
- then you know seven of them to the
- second
- sub model and you're just passing a lot
- of things uh
- in a lot of places and it becomes
- tedious whereas here you just pass the
- data
- everywhere a single variable going
- everywhere
- um and then you can just use whatever
- you need out of that data so quite a bit
- more convenient to use
- so that's the basic idea with data
- classes and also
- you know we looked at using other custom
- classes as well
- um and just the whole idea of what a
- class is what uh
- how it's relates to a data type defines
- the data type
- so um next time we're going to come back
- and cover handling errors in python
- and that will be uh wrapping up our
- segment
- on the basics in python that will
- prepare us to actually go and build out
- a full-on financial model
- in python so thanks for listening and
- see you next time
Handling Errors in Python¶
Notes¶
Error handling is generally a more advanced pattern and so we won’t put a lot of focus on it in the class. But sometimes it is the best solution to a problem.
Combining lists of different lengths is one possible application of error handling, but there are many others
Transcript¶
- hey everyone
- nick dear burtis here teaching you
- financial modeling today we're going to
- be talking about
- error handling in python which will
- conclude our segment on
- going beyond an initial python script
- the tools and skills that we need in
- python to go
- and build out financial models so
- this is going to be a quick video we're
- just going to be
- quickly reviewing error handling uh
- most people probably are not even going
- to need this it's just something to be
- familiar with in python because you may
- need it
- at certain points
- [Music]
- you know definitely it comes up a lot
- more in general programming than in
- building financial models but there are
- still cases where you
- may find it useful uh for modeling
- and then you know as you go outside the
- class and expand
- into other areas in python you'll find
- it useful as well
- so you know at this point if you've been
- following along and you've been working
- on
- all the labs and you've been uh you know
- building out the the models and examples
- along with me
- then i'm sure you've seen errors coming
- up i've also shown examples of errors
- you know syntax error
- annotation error name error uh
- you know index error there's so many
- different kinds of errors
- and when you hit an error in python code
- it stops the execution of the code
- wherever you're at as soon as it throws
- the error it's just done it's just
- it's not going to execute anything after
- that
- and sometimes you're going to be going
- through your code and you're going to
- expect
- to get an error uh that this error
- is actually something that
- is inherent to the way that the model
- works uh
- it could be you know something like you
- could set it up that
- you know you're supposed to put you know
- a number of years as an input into the
- model
- and you want to add some validation such
- that if a user
- uh you know gets less than or it puts in
- less than
- uh zero for the number of years then
- you know it could be you raising an
- error or catching the the error that
- comes out of your program and
- and then you know printing that out to
- the user hey make sure you pass a number
- greater than uh zero for
- the number of years or you know it could
- be
- something that comes up just from the
- logic of your model where you do
- actually expect to see an error
- in some or all of the cases um and you
- want to do something in response to that
- error instead of just having the code
- stop
- at that point uh
- so here's the basic structure for error
- handling
- um so um
- the structure is what's called a try and
- accept
- clause um and
- basically you try to do something and
- then if there's an error
- then you're gonna go into the accept
- um so here you know we've got
- a list defined that has two items a and
- b
- and then we're trying to uh
- look up the 11th item from the list of
- course the list only has
- two items and so there is no 11th item
- and so as we saw you know previously
- when covering lists
- uh that we're gonna get an index error
- in that case
- right um and so
- uh you know you run this code and
- it's just going to print out caught the
- error
- it's not going to fail it's not going to
- show you any index error it's just going
- to print
- caught the error and that's because we
- tried
- to look up the 11th item in the list and
- then
- this triggered the index error
- but then we have this accept clause and
- so this accept clause
- says you know whatever exception you put
- here
- it's going to look for that exception
- coming up within the try clause
- and if it does then we're all of a
- sudden going to be
- in this part of the logic
- [Music]
- so it's a totally different way to
- handle uh the flow
- in your python program versus you know
- like using conditionals or something
- like that to control flow
- um it's you know if you get an error
- we're going somewhere else in the code
- um so
- there's a lot of different possible
- applications of this and we'll look at
- an example here
- in the moment um and then you'll notice
- it's just like
- uh you know every other kind of logical
- block that we've defined in
- python you know be it for loops be it
- if statements uh function definitions
- class definitions uh now also try and
- accept
- again it's you put uh the
- you know the control statement and then
- a colon and then on the next line you
- end in
- and then whatever is indented is going
- to be running
- as part of that block that logical block
- so the try block as this code in it the
- accept block
- has this code in it because they are
- indented
- and the try and the accept have to be on
- the same indentation level
- just like when we looked at if and else
- right like if and else are like part of
- the same
- um construct here and so then the same
- thing with try and accept
- um they go together and so they should
- be on the same indentation
- level so then um
- you know just thinking about an example
- here uh so let's say
- you know you've got um you know two
- different annuities
- uh they both pay a hundred dollars a
- year for five years
- uh but one you're getting in the year
- zero and one you're getting in year
- three
- so we can define this annuity as just a
- list of a hundred five times
- and here's a nice little shortcut that
- will let you define
- something repetitive like that this will
- expand out to being
- a list with a hundred in it five times
- um and then we want to figure out
- what are the cash flows overall you know
- going up to 15 years
- or you know however many years
- so here's some code which is able to
- get to that result using error handling
- so here looking at 10 years
- and we've got these two different
- annuities um
- this second annuity is going to start in
- year four uh the first
- annuity or year three or year zero
- whatever you want to call the first year
- zero or one it's gonna start three years
- later for the second annuity
- um and we want to ultimately get the
- cash flows at the end right so
- three periods of getting just 100 and
- then two periods where they're both
- paying we get 200
- and then three more periods are just a
- hundred and then zero for the remaining
- periods is the result that we would
- expect
- of putting these two things together um
- so one way you might think to put them
- together is
- okay let me loop through the number of
- years and then
- let me go through the annuities and add
- up
- you know looking up that year's value
- from
- the annuity
- but the
- issue there is then that
- the annuities uh
- don't have equal links here this one is
- only five
- long this is eight long and so
- as you get uh to year six
- all of a sudden is trying to look up the
- sixth year in this annuity which has
- only five items
- and that's going to give you an index
- error um
- so then if we have this try accept
- handling in here
- uh if we get the index error well we're
- just not going to do anything
- that's what pass means is just uh you
- know go on ahead
- uh i don't want to do anything here
- because in that case you know we don't
- need to add anything the annuity is done
- so we just want it to keep going without
- throwing an error
- and so then when we do that then we
- ultimately get the output
- that we would expect of these two
- annuities
- combined so that's a quick overview
- on error handling in python
- definitely uh you know it's not going to
- be super common in financial modeling to
- hit this until you get to you know
- definitely more complex
- uh models but a good pattern to know
- regardless and if you're unsure about
- whether you should be applying it or you
- have questions about applying it just
- feel free to to ask me about that
- and i can give more contacts there
- so that wraps up our segment on
- going beyond an initial python script
- where now we have the basic python
- knowledge that we need
- such that we can go and build out the
- dynamic salary retirement model
- fully in python for our next major
- segment so thanks for listening and see
- you next time