Python Notes Plus
Python Notes Plus
Introduction
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
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.
Object orientation
o Python is an object oriented language.
o Every piece of data and even function and types are objects.
o The term object oriented is used to distinguish python from earlier lanaguages,
classified as procedural languages where types of data and operations on them were
not connected in the language. In object oriented programming, all data are in the
objects, and a core group of operations that can be done on some particular type of
object are tightly bound to the object and called the object’s methods.
o For example strings are objects, and strings “know-how” to produce an uppercase
version of themselves.
o Upper is a method associated with strings. And upper is a function that is bound to the
string before the dot. The function is bound both logically, and as we see in th new
notation also syntactically.
o Each type of data knows operations (methods) that can be applied to it. And it returns
a new uppercase srtring result based on s.
o Strings are immutable, so no string method can change the original string, it can only
return a new string.
o The new object syntax is
object.method( )
o Meaning that the method associated with the object’s type is applied to the object.
This is just a special function call on object.
o Another string method is a lower, analogous to upper, but producing a lower result.
o Many methods also take additional parameters between the parantheses, using the
more general syntax:
object.method(parameters)
o The first of many such methods we will introduce is count:
s.count(sub)
This wukkk count and return the number of repetitions of a string sub
that appear as a substrings inside the string
o Just as the parameter can be replaced by a literal or any expression, the object to
which a method is bound with the dot may also be given by a literal, or a variable
name, or any expression that evaluates to the right kind of object in its place. This is
true for any method call.
o Technically the dot between the object and the method name is an operator, and
operators have different levels of precedence. It is important to realize that this dot
operator has the highest possible precedence.
o Python lets you see all the methods that are bound to an object(and any object of its
type) with the built-in function dir. To see all string methods, supply the dir function
with any string.
o Many of the name in the list start and end with underscores, forexample like _add_.
These are all associated with methods and pieces of data used internally by the python
interpreter. The remaining entreis in the list are all user-level methods for strings. We
should not that some of the methods are more commonly used than others.
o Object notation have been illustrated so far with just the object type str, but it
applies to all types.
object.method(parameters)
String indices
o A string is a sequence of smaller components (individual characters), and it is often
useful to deal with parts of strings.
o Python indexes the characters in string, starting from 0. Each index is associated with a
character, and you reference the individual characters much like in a dictionary.
o len is a function which gives the length of a sequence and it works on strings.
o The indices for a string of length n are the elements of the sequence range(n), which
goes from 0 through n -1, or the length of the string minus one.
o On python you can index from the right end of the string. Since positive integers are
used to index from the front, negative integers are used to index from the right end.
String Slices
o It is sometime necessary to extract larger pieces of a string than a single character and
the this is called slicing.
o Forexample when we index a variable s
s [startindex : pastindex]
This refers to the substracting of s starting at index startindex and
stopping just before index pastindex.
o It confuses many people that the index after the colon is not the index of the final
character in the lsice. The second index is past the end of the slice.
o If we omit the first index, the slice starts from the beginning. If you omit the second
index, the slice goes all the way to the end.
o Python evaluates slices in a more forgiving manner than when indiexing single
charachers.
o A useful strig method that uses the ideas of indices and slices is find.
o Syntax options for find method with a string
o Return the integer index in the string s of the beginning of the first complete
occurrence of the substring sub. Is sub does not appear inside s, return -1. The vakue
would be an impossible if sub must not have been found. If parameters start and end
are not included in the parameter list, the search is through the whole thing s. If an
integer value is given for a start, the search starts at index start. If an integer value is
given for end, the search ends before index end. In Other words if start and end
appear, then the search is through the slice s[start: end], but the index returned is still
counted from the beginning of s.
o Here is a place that you want to refer to the method itself, not invoke the method, so
note that you get help for s.find not for s.find ( ).
o The python documentation for a function with one or more parameters, you may see
what looks like a final parameter/. Ignore it. It documents a technical restriction on
parameters. It is not actually a parameter.
o Indexing and slicing works on any kind of python sequence, so you can index or slice
lists.
o Unlike strings, lists are mutable. Indices and slices can also be used in assignment
statements to change lists
Index Variables
o Variables or expressions are almost always used for indices.
Slit
o The syntax option for split method with a string s:
s.split ( )
s.split(sep)
o The first version splits s at any sequence of whitespace (blanks, newlines, tab) and
returns the remaining parts of s as a list. If a string sep is specified, it is the separator
that gets removed from between the parts of the list.
Join
o Join is roughly the reverse of split. It joins together a sequence of strings. The syntax is
rather different. The separator sep comes first, since it has the right type (a string).
sep.join(sequence)
o It will return a new string obtained by joining together the sequence of strings into one
string, interleaving the string sep between sequence elements.
o The methods split and join are often used in sequence.
Appending to a list
o Lists have a method called append. It modifies the original list. Another word for
modifiable is mutable. Lists are mutable. Most of the types of objects considered so far
(int,str,float) are immutable or not mutable
o The fact lists areare modifiable is useful I loop where we can accumulate a new list.
o .append takes only one argument at a time.
Sets
o We have learned from maths that a sets is a collection that does not allow repittions (a
set automatically removes repetitions suggested).
o Python has a type set. Like many type names, it can be used to convert other types
(collections) to sets and removes duplicates.
o A set is unordered. SO literals are enclosed in braces. Like other collection, a set can
be used as a sequence in for loop.
Constructors
o In cases a new object of a specified type is constructed and returned, the functions are
called constructors.
Graphics
We need the graphics.py file in the same folder as any graphics program we write.
A graphics introduction
o