Python For Finance Notes: III. Jupyter Notebook Guide
Python For Finance Notes: III. Jupyter Notebook Guide
At the most fundamental level in the computer, there are instructions built
into the hardware. These are very simple instruction, peculiar to the hard ware
of your particular type of the computer. The instructions are designed to be
simple for the hardware to executed, not for humans to follow.
Higher-level languages allow computer programmers to write instructions.
No computer understands the high-level instruction directly, so it must be
translated to machine language.
Sample Program
Integer Arithmetic
Python uses the doubled division symbol // for the operation that produces just
the integer quotient, and introduces the symbol % for the operation of finding
the remainder.
We can use the / division symbol to get the float answer of a division.
The remainder operation is defined for all integers, even a negative divisor.
Dividend = quotient * Divisor + Remainder
Remainder = Dividend – quotient * Divisor
With positive numbers the integer quotient is always no bigger than the real
quotient. And python requires that this is true, no matter what the signs of the
operands:
Strings Part I
Expressions like 27 or ‘hello’ are called literals coming from the fact they
literally mean exactly what they say. They are distinguished from variables who
value is not directly determined by their name.
The sequence of characters used to form a variable name ( and names for other
python entities later) is called an identifier. It identifies a python variable or
other entity.
There are some restrictions on the character sequence that make up an
identifier.
The characters must all be letters, digits, or underscores, and
must start with a letter. Punctuation and blanks are not allowed.
There are some words that are reserved for special use in python.
We may not use these words as our own identifiers. They are easy
to recognize in idle because they are automatically colored
orange.
There are also identifiers that are automatically defined in python, and that
you could redefine, but you probably should not unless you really know what
you are doing!
Python is case sensitive. The identifiers last, Last, LaSt are all different. Be
sure to be consistent.
What is legal is distinct from what is conventional or good practice or
recommended. Meaning names for variables are important for the humans who
are looking at programs, understanding them, and revising them. Things we can
do to make our programs easily readable by others include:
Underscore separated: putting underscores in places if blanks
Using camel-case, omitting spaces and using all lowercase, except
capitalizing all words after the first
Python interpreter can help us type an expression and immediately see the
result of its evaluation. We can use this to test out syntax and maybe do simple
calculator calculations.
In a program run from a file, if you want your program to display something,
you can give explicit instructions with the print functions.
The print function will print as strings everything in a comma-separated
sequence of expressions, and it will separate the results with single blanks, and
advance to the next line at the end, by default. Note that you can mix types:
anything that is not already a string is automatically converted to its string
representation.
We can also use it with no parameters like, print(), to only advance to the next
line.
Strings Part II
Dictionaries
To keep the computer doing useful work, we need repetition, looping back over
the same block of code again and again. There are two python statement types
to do that, for loops and while loops.
Two preliminaries
o The value of already defined variables can be updated. This will be
important in loops. To prepare for that we first follow how variables can
be updated in an even simpler situation, where statements are just
executed in textual order.
o Sequence types are used in for loops. We will look at the basic sequence
type: list.
Updating Variables.
o It is helpful to create a table that will track the order of execution will
always be clearer. In a simple sequential code, that follow the textual
order of the program, we can keep track of the current variables. And
this will be called playing computer.
The List type
o Lists are ordered sequences of arbitrary data. Lists are the first kind of
data discussed so far that are mutuable: the length of the sequence can
be changed and elements substituted.
o The basic forat is a square-bracket enclosed, comma-separated list of
arbitrary data.
The range Function, Part I
o There is a built-in function range, that can be used to automatically
generate regular arithmetic sequences.
o The range pattern for use is
range(sizeOfsequence)
o The syntax will generate the integer, one at a time, as needed. If you
want to see all the results at once as a list, you can convert to a list.
The resulting sequence starts at 0 and ends before the paraemeter. One
important propeoerty of sequences generated by range(n) is that the
total number of elements is n: The sequence omits the number n itself,
but includes 0 instead.
o With more parameters, the range function can be used to generate a
much wider varietu of sequences.
Basice for loops
o The for loop has the heading starting with for,followed by a variable
name(count in this case), the word in some sequence , and a final colon.
As with definition and other heading lines, the colon at the end of the
line indicates that is consistently indented block of statements follows
to complete the for loop.
for item in sequence:
indented statements to repeat; may use item
o The block of lines is repeated once for each element of the sequence.
And when we are executing step by step, we should note that the for
loop heading serves two purposes:
Each time the heading lines executes, it implicitly assigns a
new value to the variable name you use in a place of item.
After each execution of the heading line, the statements in
the indented block are executed, generally making use of
the new value for the variable assigned in the heading.
o When playing computer with a loop, the same line numbers can reappear
over and over, because the for loop heading line and indented body
under it are each executed repeatedly. Each time one of these lines is
execured, it must be listed separately, in time sequence.
o In a file, where the interpreter does not need to respond immediately,
the blank line is not necessary. Instead, as with a function definition or
any other format with an indented block, you indicate being past the
indented block by dedenting. Here the following print statement has the
same level of indentation as the for loop heading. Because they have the
same level of indentation, they are execueted in sequence.
o Loops are one of the most important features in programming. While
the for loop syntax is pretty simple, using them creatively to solve
problems (rather than just look at a demonstration) is among the biggesr
challenges for many learners at an introductory level. One of the
simplest patterns is illustrated in all of the for loop examples so far, a
simple for-each loop. FOR EACH elemenet of the sequence, do the same
sort of thing with it. Stated as more pythonic pseudo-code:
for each item in sequence:
do somethings with the current item
o In the for loop example we used, something is printed that is related to
each intem in the list. Printing is certainly one form of “do something”,
but the possibilities for “do something” are completely general!
o A programmer should increase their ability to abstract the general
pattern from the group of examples. This essential for using loops
effectively.
Simple Repeat Loop
o A simpler for loop usage is when you want to repeat the exact same
thing a specific number of times. In this specific case, only the length of
the sequence, not the individual elements are important. We can use
the range function since it provides an easy way to produce a sequence
with a specified number of elements.
o When reading a code, we must look at the variable names as they are
introduced and see where they are used later.
o We should remember that we can name a variable _(just underscore)
Successive Modification Loops
When we need a way to change the value of number that
will work each time through the loop. The pattern of
counting is simple, we can describe the pattern by saying
each successive number is one more than the previous
number. We need to be able to change the original variable
so it is one more than it was before.
o Some characteristics of loops are
may contain several variables
one way a variable can change is by being the variable in a
for loop list.
Another way to have variables change in a loop is to have
an explicit statement that changes the variable inside the
loop, causing successive modifications.
o There is a general patterm to loops with successive modifications of a
variable
The variables to be modified need initial values before the
loop.
The loop heading cause the repetition. In a for-loop, the
number of repetitions is the same as the size of the list.
The body of the loop generally “does something”
There is a code inside the body of the loop to set up for the
next time through the loop, where the variable which
needs to change gets transformed to its next value.
o To the basic syntax will be
Initialize variables to be modified
Loop heading controlling the repetition:
Do the desired action with the current variables
Modify variables to be ready for the next action
o Functions are handy for encapsulating an idea for use and reuse in a
program, also for testing. We can write a function to a number a list,
and easily test it with different data.
Accumulation Loops
o Suppose you want to add all the numbers in a list, and since the list may
be arbitrarily long, we must find a pattern so that we can keep reusing
the same statements in the loop. And we are using each number in the
sequence in order.
o The trick is to use the same line of code the next time through the loop.
In the suitcase program, the two middle line are an if statement. The indented
part will only be executed as long as the if statement is true. In any event,
when you have finished with the if statement (whether it actually does
anything or not), go on to the next statement that is not indented under the if.
The general python syntax for a simple if statement is
If condition:
indentedStatementBlock
If the condition is true, then do the indented statements. If the condition is not
true, then skip the indented statements.
For an if-else statements, you will get different results depending on the input.
For the clothes.py program we wrote on jupyter, the middle four lines are an
if-else statements. Like in the if statement, the if heading is executed when
the original condition is True. In the if-else form this is followed by an else:
line, followed by another indented bloack that is only executed when the
original condition is false. In an if-else statement exactly one of two possible
indented blocks is executed.
In the same program, a line is also shown dedented next, removing
indentation, about getting exercise. Since its dedented, it is not a part of the
if-else statement: Since itd amount of indentation matches the if heading, it is
always executed in the normal forward flow of statements , after the if-else
statements whichever block is selected)
The general python if-else syntax is
If condition
Indented Statement Block for True Condition
else:
Indented Statement Block For False Condition
These statement blocks can have any number of statements, and can include
about any kind of statement.
All the usual arithmetic comparisons may be made, but many don’t use
standard mathematical symbolism, mostly for lack of proper keys on a standard
keyboard.
We should be careful not to put a space between the two-symbol Python
substitutes.
It is common error to use only one equal sign when you mean to test for
equality, and not make an assignment!
An equality check doesn’t make an assignment. Strings are case sensitive.
Order matters in a list.
Generally, there are a number of ways you might solve the same problem.
Other Boolean Operators
There are also other boolean operators thata re applied to types other than
numbers.
A useful boolean operator is in, checking membership in a sequence
The same operator can be used with not, as not in, to mean the opposite
It will have two versions
Item in sequence
Item not in sequence