Anything you want to know about me?
A ship in port is safe; but that is not what ships are built for. Sail out to sea and do new things.
John Augustus Shedd
Never be the brightest person in the room; then you can’t learn anything.
James Watson
The most dangerous way to lose time is not to spend it having fun, but to spend it doing fake work.
Paul Graham
Any sufficiently advanced technology is indistinguishable from magic.
- Arthur C. Clark
What did you learn about bicycles?
Why did we read about bicycles?
To me programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge.
David Sayre
The professor said on Monday he would give an exam.
One morning, I shot an elephant in my pajamas. How he got in my pajamas I don’t know.
—Groucho Marx
Formulating problems such that solutions can be represented as computational steps
scannedstored in the headcounter in the head can be incrementedscanned is emptyscanned matches storedcountercounter if stored matches
scannedCount the number of items on the tape
counter should be equal to the count of the items on the
tape when the machine stops
scanned is emptycounterSearch through list for an item matching stored
The machine head should stop with the head on the first match if there is a match or stop after the end of the list if there is no match.
scanned matches storedscanned is emptyCount the number of matching items in a list
counter should be equal to the count of matching items
on the tape when the machine stops
counter if scanned matches
storedscanned is emptyAn expression is a syntactic entity in a programming language that may be evaluated to determine its value.
+ Addition- Subtraction* Multiplication/ Division"Hello, World!" (string)7 (integer)Follows conventions from algebra
True or False| Operator | Name |
|---|---|
< |
Less than |
> |
Greater than |
<= |
Less than or equal |
>= |
Greater than or equal |
== |
Equal |
!= |
Not equal |
True or False when operating
on True and False valuesnotandor| A | B | Q |
|---|---|---|
| F | F | F |
| F | T | F |
| T | F | F |
| T | T | T |
| A | B | Q |
|---|---|---|
| F | F | F |
| F | T | T |
| T | F | T |
| T | T | T |
What is the truth table for the following expression?
Follows conventions from algebra
A variable is a named container for a value
print("Hello, world")Reserved words may not be used as variable names
and continue finally is raise
as def for lambda return
assert del from None True
async elif global nonlocal try
await else if not while
break except import or with
class False in pass yield
input(prompt=None)str (string)prompt will be shown to user if providedint converts strings to integersint can be used to convert values into integerstypetype can be used check the type of a valueint does not modify value in placeif statement is terminated by a :if control flow
diagram// performs integer division% is the modulo operator and computes the remainder
after divisionWhy would we want a modulo operation?
if check
failselse+
operator* operatorif conditionally executes codeelif conditionally executes alternative codeelse executes if no other conditions are metHow would we approach building a quiz like this?
exit can be used to immediately terminate a
program.input and print statements2 + 3)2 <= 3)a=3)if, elif,
else)Pokemon Nesting Example
try
blockpasspass keyword is valid in many placesA function is a named sequence of statements that performs a computation
int is a functionmin and max return the minimum and maximum
of their argumentsmin and max can also operate on iterables
such as stringslen can be used to return the length of a valueint, float, and str can be
used to convert typesimport math can be used to create the math object used
to access the module. characterhelp can be used to provide information about an
objecthelp(math) provides information about available math
functionsrandint returns a random integer between boundschoice selects one item from an iterableprint is an example of a void functioninput is an example of a fruitful functionWe can reimplement min ourselves
Functions may call other functions
How do we know if software works?
Software testing is the act of checking whether software satisfies expectations.
How do we know if this code works?
assert is a simple tool for thisassert will raise an exception if its input expression
if falseHow would we test get_tip?
Modular design emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.
Separation of concerns is a design principle for separating a computer program into distinct sections.
The separation of concerns, which, even if not perfectly possible, is yet the only available technique for effective ordering of one’s thoughts, that I know of.
Edsger Dijkstra
Architectural boundaries should be separated so that changing one part of the system has no effect on any other part of the system.
Bob Martin
if can be used to conditionally execute a section of
codeelif and else can provide
alternativesinput, min,
etc)defWe can shorten common reassignment using augmented assignment:
while to perform operations multiple
timeswhile loop will
execute in advancewhile accepts a conditional that will stop iteration
when falsebreak can be used to terminate iterationcontinue can be reused to skip the remainder of an
iterationUse the following to get problem input:
for keyword provides definite iterationbreak and continue can be used with for as
expected[ and
])forrange is a function that returns value for use in
iterationforfor supports an else clauselen and sum in
simple casesCould we compute the mean without using a loop?
How can we count the words in a string?
[]forin operator can be used with stringsin expression will return true if the value on the
left is contained within the value on the right== checks for equality as expected< and > are a little more
complicatedCreate a program to print every other letter in a string
Create a program to find a word in a string and print the position of the word
dir can be used to list methods available on an
objectupper can be used to uppercase a stringlower can be used to lowercase itHow could we compare strings ignoring case?
find can be used to get the position of a
substringstrip returns a copy of the string with leading and
trailing whitespace removedstartswith will return True if the string begins with
the supplied prefixcount will count the number of non-overlapping
substrings in some text:) is used to separate the start and end
indexformat method on stringsformat method in this classf should be used before the opening quote of the
string literalCreate a program that will capitalize the first word in a provided sentence.
Create a program that will search a string for a word and display the word along with the 5 characters before and 5 characters after it.
open function may be used to open a file\n
escape sequencereadline method will return the next line as a
string valuereadlines method will return an iterable of all
linesopen function to get a file handleread to load a string from a filetry and except to handle these
errorsexcept blocksprint all capitalized words in a user-selected
file.Count all if, elif, and else
keywords in a program
filename = input("Filename:")
try:
handle = open(filename)
except FileNotFoundError:
print("File not found")
exit(1)
contents = handle.read()
count_if = 0
count_elif = 0
count_else = 0
for word in contents.split():
if word == "if":
count_if += 1
elif word == "elif":
count_elif += 1
elif word == "else":
count_else += 1
print(f"if: {count_if}")
print(f"elif: {count_elif}")
print(f"else: {count_else}")try and except can be used to deal with
exceptionswith can be used to automatically close a filewith statement can be used with all context
manager typeswith always closes the file, even when exceptions are
raisedWrite the first 1000 positive integers to a file
Read the values from that file one at a time and write their squares to a second file
with statement can be used to automatically close
files[1, 2, 3]["a", "b", "c"][]IndexErrorin operator is supported on listsfor is useful for reading, but doesn’t allow
modification directlylen and
rangeCreate a Python program that will add 1 to every element in a list.
lenCreate a Python program that will count all individual elements in nested lists.
+ operator can be used to concatenate lists+ operator may be used for appendingCreate a program that builds a list of 10 randomly generated numbers
* operator can be used to duplicate listscopy method can be used for this[:]) can also be usedappend method can be used to add an item to the end
of a listextend method can add many elements to a listsort method can be used to sort list elements in
placesort always returns NoneNoneCreate a Python program that prints the three largest numbers in a list
pop will remove and return an element at a position (or
the last element by default)del can be used to remove the element without returning
it (can use slices)remove will remove the element by valueCreate a Python program to remove all single-digit numbers from a list
len, max,
min, and sumsum won’t work properly with strings, for examplelist constructor can be used to create a list from
a stringis operator can be used to test if two values are
the same object== to compare listsWrite a Python function that will return True if and
only if the two lists contain the same items but are not the same
list.
a = [1, 2, 3]
b = a
print(a is b)
Adjust the following program so that first_half does not modify the list it is passed
{}Create a program that builds a dictionary that maps the days of the week to the time you need to wake up on these days.
{}in operator can be usedin will return True if the key exist in the
dictionaryCreate a program that can count the number of occurrences of each word in a text
values method can be used to get values as an
iterablet = 1,tuple
constructor or empty parens (())tuple constructor can also be used to convert other
types into tuplesWrite a concise program to swap the values in two variables,
a and b
Write a Python program that creates a list of all words in a sentence. The list should be sorted by the length of the word, smallest first. For example, the sentence “She is a girl” should produce:
['a', 'is', 'She', 'girl']
items can be used to get keys and values from a
dictionaryfor loopUse enumerate to print only the letters with an
even-numbered index in a string.
Use zip to create a list of each pair of letters in a string. For example, the string “abcd” should produce the following list:
for loopmap is provided to simplify
this taskmap takes a function and applies it to all items in an
iterable return a new iterablelambda keyword can be used to facilitate thisCreate a square function using lambda
instead of def.
lambda and map can be combined to quickly
perform operations on entire listsif clausegenerator object is an iterable that can only be
iterated oncefordict constructoryield keyword can be used to emit values from
generatorsCreate a generator that will yield every odd number that is not divisible by 5.
print and input) interact
with the system in text mode<a> tagshref) may be included to link to
another documentfrom flask import Flask, request, session
import languagemodels
app = Flask(__name__)
app.secret_key = "FyJYMJmwZUWASo5J"
@app.route("/")
def home():
if not "history" in session:
session["history"] = ""
usertext = request.args.get("usertext", "")
if usertext:
session["history"] += f"<p>User: {usertext}"
response = languagemodels.do(f"Respond to a user: {usertext}")
session["history"] += f"<p>Bot: {response}"
return f"""
{session['history']}
<form action=/>
<input type=text name=usertext autofocus />
<input type=submit />
</form>
"""How can we help thousands of people work together to write millions of lines of code?
git init.git metadata directorygit status can be use to check the current state of the
repository> git init
Initialized empty Git repository...
> git status
On branch main
No commits yet
nothing to commit (create/copy files and use "git add" to track)
git add can be used to track and stage a file> git add main.py
> git status
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: main.py
git commit can be used to create a new commit-m flag can be used to provide a message-a flag will commit all changesgit log can show the commit historyfind method can be used to get the location
of one string in anothersplit method can be used to split
stringsre modulesearch method can be used to find a matching
span in a stringNone if no match. will match any characterCreate a regular expression that can match all 5 letter words that start with “c”
Grammar Automaton (Computer)
Unrestricted Turing Machines Context Free Pushdown Automata Regular Finite State Automata
+*Create a single, concise regular expression to match a string with 0
or more a’s followed by at least 1 b followed
by at least 1 c. Examples:
abcbcaabbccThese should not match:
acbacTrue if a string matches from the
beginningmatch or searchfindall function can be used for this purpose. are not matched
literally. ^ $ * + ? { } [ ] \ | ( )
[]-” to indicate a range of characters\d - any decimal digit\s - any whitespace\S - any non-whitespace\w - any alphanumericsub can be used to perform regex replacements() can be used to indicate which portion of an
expression to extract{} can be used to specify an exact count on
the preceding character classsearch returns a match object on success0 is always the full matchPrompt command param1 param2 … paramN
ls command can be used for this in most shellsdirRun calculator using Windows:
Run thonny using Bash:
strintlistrange.”Create a Student class with class_level and
gpa attributes
Add a set_gpa method to your Student class
that will set their GPA to a supplied number
self is chosen as the name for this parameter by
convention
Comments
#symbol