MCS 275 Spring 2022
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 detail in optional texts and the online MCS 260 materials from my Fall 2021 course.
* If I mention things today that are completely new to you, please let me know afterward.
The most comprehensive optional text is
Written in 2013, so it discusses Python 3 and Python 2. Since then, Python 2 has been phased out. We only talk about Python 3.
I'll do most examples as live coding today.
Options to study this outside of lecture:
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
See Lutz, Chapters 4-6 and MCS 260 Lec 3.
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.
See Lutz, Chapter 7 and MCS 260 Lec 7.
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 6.
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.