MCS 275 Spring 2021
Emily Dumas
Start our quick tour of Python, summarizing some material I think you saw in a previous course*.
I'll indicate where you can find more detailed coverage in Lutz (textbook) or in the online MCS 260 materials from my Fall 2020 course.
* If I mention things today that are completely new to you, I'd like to know. Email or send a message in discord.
Learning Python, 5ed was written in 2013 and so it discusses both Python 3 (our focus in MCS 275) as well as an older language (Python 2) that is no longer supported and which we won't discuss or use at all.
I'll do most examples as live coding today.
For study outside of lecture, I wrote a larger collection of examples that roughly follow the same outline:
Two ways to run Python code:
See Lutz, Chapter 3 or MCS 260 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
Lists are mutable ordered collections of elements, accessible by integer index.
[260,275,"hello",True,None,None,-1.5]
Dictionaries (dicts) are mutable key-value mappings. Index like lists, but use key instead of position.
{ "name": "Stinger", "age": 403,
"species": "space wasp", "hostile": True }
Strings support some list-like features, such as indexing and slicing.
Lists have useful methods such as .lower()
, .startswith(...)
, .format(...)
, and many more.
If statement (or conditional) runs a block of code only if a condition is True. Elif/else allow chained tests.
if GREAT:
RUNS_IF_GREAT_IS_TRUE
elif OKAY:
RUNS_IF_OKAY_IS_TRUE_AND_GREAT_IS_FALSE
else:
RUNS_OTHERWISE
Non-boolean conditions are coerced: empty list, empty dict, empty string, None, and zero map to False.
While: Keep going until a condition becomes False
while CONDITION:
STUFF_TO_DO # should modify things in the condition
For: Take items (list elements, dict keys) out, one at a time, and do something with each.
for ITEM in CONTAINER:
STUFF_TO_DO # should use the ITEM
See Lutz, Chapter 13 and MCS 260 Lec 7.
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.