MCS 275 Spring 2024
Emily Dumas
Reminders and announcements:
These slides may be useful for self-study. I may not show them all today.
Also useful: MCS 260 materials and Lutz's book
Use the down arrow to see slides about things we already discussed in Lecture 1.
Two primary ways to run Python code:
See Lutz, Chapter 3 or MCS 260 2021 Lec 2.
Create new vars by assignment, name = value
Dynamically typed: No need to specify the type of a variable, nor for it to remain the same.
Basic types include: int, float, boolean, string, None
See Lutz, Chapters 4-6 and MCS 260 Lec 3.
Strings have useful methods such as .lower()
, .startswith(...)
, .format(...)
, and many more.
See Lutz, Chapter 7 and MCS 260 Lec 7.
list
- ordered collection of items, access by 0-based indexdict
- key-value mapping. Given a key, it returns the corresponding value.tuple
- like a list, but immutableset
- like a dict but there are no values.Example list
[260,275,"hello",True,275,None,-0.5]
Example dict
{ "name": "Zorlax", "age": 1645,
"species": "Tau Cetian robot", "hostile": True }
Negative indices get elements based on position relative to the end. Index -1
means the last element.
Slices get a contiguous sublist. L[a:b]
gives a list consisting of all L[k]
such that a ≤ k < b
.
Slices can also get evenly spaces items with L[a:b:stepsize]
Can be changed by item assignment (L[i] = newval
) and various method calls (e.g. .sort
, .append
, .pop
).
Mutations (statements that change list contents) often return nothing.
Strings support some list-like features, such as indexing and slicing.
But unlike lists, strings are immutable.
If D
is a dict, the boolean expression
x in D
checks whether x
is a key.
Conditionals (if
)
Loops (for
, while
)
(We won't discuss match
, which is new in 3.10)
Check a series of boolean expressions in order. As soon as one is true, run the code block below it.
if CHECKED_FIRST:
DO_THING_A
elif CHECKED_SECOND: # elif means "else, if"
DO_THING_B
elif CHECKED_THIRD:
DO_THING_C
else:
DO_THING_D
# Now exactly one of A,B,C,D has happened
Non-boolean conditions are coerced if they appear where a boolean is expected.
Empty containers (list, dict), empty string, None, and zero become False, any other value becomes True.
While: Keep going until a condition becomes False
while CONDITION:
DO_THING # maybe makes CONDITION true next time
For: Take items (list elements, dict keys) out and do something with each.
for ITEM_VARNAME in CONTAINER:
DO_THING # should use ITEM_VARNAME
See Lutz, Chapter 13 and MCS 260 Lec 6.
break
- jump out of the nearest enclosing loop immediately
continue
- jump back to the nearest enclosing loop immediately
open(filename,mode,...)
opens a file and returns a file object. Mode string selects reading ("r"), writing ("w"), ...
Methods of the file object perform input/output (I/O).
Read/write text to text files ("t" in mode), bytes to binary files ("b" in mode).
.close()
a file when finished.
The basics are in Lutz, Chapter 9 and MCS 260 Lec 13 and Lec 14.
def contains_all_digits(x):
"""Does integer x uses all decimal digits?"""
for c in "0123456789":
if c not in str(x):
return False
return True
Interactive use:
>>> contains_all_digits(2*5)
False
>>> contains_all_digits(2**94)
True
The first non-comment statement in any Python file, function, class, or method should be a string literal on a line by itself.
Python remembers that string as a description of the file/function/class/method. Called a docstring.
Anywhere else you want to put explanatory text, use a comment.