Class 16 — Wednesday, September 30
Knowing what you know
Though the past is past – It is still an augury – Of future tidings
Always be mindful. — Make sure what you are doing, — Is what you intend.
Look both ways
Agenda
- Chronicle what we know or should know
Examples
- Program test1-review.py – to be determined during class.
- Module url.py
Recent Test 1 solutions
Recent Test 1 artifacts
Review module documentation
- Built-in functions.
- Module str.
- Module list.
- Module url.
- Module random: our only interest are its functions
seed()
andchoice()
.
Test 1 mind trick
- Power pose before test — allegedly helps with endorphins.
Epistles
Test logistics
- Test 1 is Friday, October 2.
- You can do the questions in any order that you choose.
- Class personnel cannot help you debug your answers.
- For people without timing accommodations, once you start the test you will have 75 minutes to complete the test, along with a 15-minute grace period to submit your solutions.
- For people with timing accommodations, once you start the test you can have up to your approved number of minutes to complete the test, along with a 15-minute grace period to submit your solutions.
- You are responsible for keeping within your accommodation time.
- You are responsible for submitting for your work. Check that you have done so. Do not submit once your testing time is up. Late submissions will not be graded.
- • During the test you can access the course module descriptions and the course Python information sheet.
- During the test you are not to access past code (yours, ours, or anyone else's).
- Before starting the test, close all PyCharm tabs to past examples.
- Shortly before testing begins there will be no access to other parts of the class website.
- Access to those parts will remain unavailable until after everyone completes the test.
- Unless there are exceptional circumstances, all students living in the continental United States are to take test at 2:00 PM on Friday.
- All students need to complete the test by Saturday October 3 @ 3:30 PM EDT. Uploading will be turned off then.
- The test has two parts. You can do the questions in any order that you choose.
- Part 1 consists of twenty short answer questions available on Collab. Your time to complete the test begins with accessing the short answer questions. You are not to use PyCharm for any of the short answer questions.
- On the Collab site you will see two versions of Part 1. They have the same questions. One is for students in general; the other is for students with SDAC extended time accommodations.
- Part 2 consists of five programming problems to be solved using Pycharm and uploaded to the class website.
- The PDF description of the programming problems requires a password. The password is made available at the start of the short answer questions.
Chrestomathics
- An algorithm is doable structured communication without ambiguity.
- A program is an algorithm written in a language that can be carried out on a computer.
Development and translation
- Python is an interpretive programming language designed for automating tasks.
- There are compilers that can be downloaded for most computers to execute Python programs.
- There are IDEs like PyCharm for computers to develop Python code.
How Python works
- Executes one line at a time, in order from top to bottom (except
for
repeats some lines).
- Evaluates literals, expressions, variables, function, and method invocations according to operator precedence.
Values and types
- All values have a type and an identity. Built-in functions
type()
andid()
return respectively the type of a value and its identity. The identity of a variable is a reference to where its value is stored in computer memory.
- The simple value (primitive) types are
int
,float
, andbool
. Primitive type values have no behaviors.
- The values (objects) of types such as
str
andlist
do have behaviors. Behaviors are implemented as methods (message functions). A method function invocation tells its object to carry out a behavior. For example, ifs
is a string, thens.lower()
returns a new copy ofs
where are letters ins
are in lower case form in the copy.
- Literal values are composed of explicit strings, numbers, and logical values like
3
,0.1415
,True
,[
2,
'abc'
,5.85
]
.
- Operators like
+
,/
,//
,%
, and**
evaluate their operands and return the value of the corresponding mathematical operation save Python limitations on decimal representations.
str
- Once created
str
values are immutable character sequences (there is no function, method, or operator that can modify an existing string).
- Escape sequences, like
'\n'
represent the new-line character.
- Operators
[ i ]
and[ i : j ]
can retrieve substrings.
- Operator
+
produces a new sring formed by concatenating its operands.
- Built-in function
len()
to find how many characters there are
- Methods like
find()
andupper()
return values.
range
range( i , j )
is the sequence of integer values fromi
toj-1
.
list
- Literal values like
[]
and[ 1, 'two', [ 3, 3.0 ] ]
.
- Operators
[ i ]
and[ i : j ]
can retrieve or modify elements or sublists
- Operator
+
with list operands produces a new list by concatenating the elements of its list operands.
- Operator
+
cannot be used when only one element is a list.
- Operatop
in
checks if a value is within the list can be a range or a list.
- Functions like
len()
,max()
, andsum()
to analyze the contents of a list.
- Method functions like
index()
return values.
- Method functions like
append()
andsort()
that modify the list in place (and returnNone
).
for
loops
- Repeat statements by iterating over a sequence of values. The sequence is a typically list or a
range
, but can also be a string.
for item in sequence :
statement1
statement2
...
statementn
In the above, iterator variable
item
takes on each of the values ofsequence
in turn. For each of those values,statement1
,statement2
,...
, andstatementn
are repeated.
- A
for
loop inside anotherfor
loop is called a nested loop.
for
loops can be used to build up (accumulate) a result.
- If the result is to be a sum, then the accumulator is initialized before the loop to
0
and increased within the loop using numeric operator+
.
- If the result is to be a string, then the accumulator is initialized before the loop to
''
and added to within the loop using string operator+
. Observe that''
is a string of length0
and different from the string' '
which is a string of length 1 that consists of a single splace.
- If the result is a list, then the accumulator is initialized before the loop with
[]
and added to within the loop usingappend()
.
- If the result is to be a product, then the accumulator is initialized before the loop with
1
and increased within the loop using numeric operator*
.
Producing values
- Values are produced whenever Python evaluates an expression.
- Anytime an expression is encountered it is evaluated.
- Anything following an assignment operator is an expression.
- Any argument to a function or method is an expression.
- The operand(s) for an operator are expression(s).
- An expression can be composed from literals, variables, operators, and sub-expressions.
Functions and methods
- A built-in function invocation does not have an object to which its actions are targeted; e.g.,
max( a, b )
returns the larger of valuesa
andb
.
- A method is named piece of code that manipulates the object to which it is targeted (dotted); e.g., in invocation
s.capitalize()
methodcapitalize()
examiness
to produce and return a copy of strings
with the first character capitalized and the other characters in lowercase.
- Whenever a function or method is invoked it, returns a value, even if that value is just
None
(like it is forprint()
anda.append()
).
Library
- A library is a modue of related functions and values that must be imported to gain access to them.
- Standard library
math
provided access to a wide variety of mathematical computations and values; e.g.,math.sqrt()
,math.sin()
, andmath.pi
.
- Standard library
random
provides ability to generate random values. The most important functions for us are
random.randrange( a, b )
returns a random integer froma
tob-1
.
random.choice( s )
returns a random value from sequences
.
random.shuffle( s )
returns a new sequence whose values are a scrambling of the values of sequences
.
random.seed( s )
usess
to set up the initial configuration of the Python random number generator.
- Local library
url
provides web access
url.get_contents( link )
returns the contents of the web resource indicated by web locationlink
.
url.get_dataset( link )
returns the contents of the web resource indicated by web locationlink
as a dataset sheet whose cell values are either string,int
,float
, orbool
as appropriate.
Web processing
- Suggest redownloading local module url.py.
- Use
url.get_contents()
to get the contents of a web file.
- Use
url.get_dataset()
to get the contents of a web dataset.
Errors
- Syntax errors are illegally formed Python instructions. This web page epistle might prove useful in dealing with syntax errors.
- Semantic errors are actions not doing what is intended.
Gotchas
- Ignoring the Bill Murray's Rule of Life — baby steps to obtain your goals.
- Ignoring the Fernando Lamas' Rule of Life — looking good makes a life complete.
- Consistent use of whitespace around operators and blank lines make mindfulness easier to obtain.
- Forgetting the Law of Cole.
- Not reading the complete description before starting to problem solve
- Ignoring the input order
- Not parsing (converting) the input into the needed values
- Not converting a string to a number using
int()
orfloat()
or to a Boolean value usingbool()
.
- Output expectations
- Improper accumulation
- Combining a string and a number using the
+
operator
- Using only the first or last value of a range or sequence to compute result
- Not checking whether your solutions match given test run expectations
- Not mindfully writing and reading your solution — you must understand what you are writing
- Mindfullness makes your computational journey clearer and easier
- Corollary: use
print()
statements when developing code to document computational progress and comment out those statement before submitting
- Functions use parentheses; lists use brackets. Remember this.
- Functions must always have parentheses. Remember this.
Datasets
- A dataset is a collection of informations arranged as list of rows, where each row is a list of cells (dataset value).
- The basic way of accessing the rows in the dataset follows.
dataset = ... # get the dataset
... # set up dataset processing (if needed)
for row in dataset : # consider rows one by one
# process current row of the dataset
... # process the row
... # finish off dataset (if needed)
- The basic way of accessing the individual cells in a dataset is row by row.
dataset = ... # get the dataset
... # set up dataset processing (if needed)
for row in dataset : # consider rows one by one
# process current row of the dataset
... # prepare to process the cells (if needed)
for cell in row : # consider cells of the row one by one
# process the current cell for the row
... # process the cell
... # finish off row (if needed )
... # finish off dataset (if needed)
- To create a copy of a column of a dataset
dataset = ... # get the dataset
c = ... # get the column
column_copy = [] # need a cell accumulator
for row in dataset : # consider rows one by one
# get cell from row' column c
cell = row [ c ] # get the cell in column c
column_copy.append( cell ) # copy the cell into accumulator
... # analyze the column
© 2020 Jim Cohoon | Resources from previous semesters are available. |