Lecture 2

Python tour

Types, control structures, I/O

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 2: Python tour

Reminders and announcements:

  • Read the syllabus.
  • Discord open (invite link on Blackboard).
  • Homework 1 will be due Noon on Wed Jan 17. Not posted yet.

Notes for self study

These slides may be useful for self-study. I may not show them all today.

Also useful: MCS 260 materials and Lutz's book

Cover of Learning Python by Mark Lutz

Use the down arrow to see slides about things we already discussed in Lecture 1.

Scripts and REPL

Two primary ways to run Python code:

  • One statement at a time, in interactive mode, also known as the REPL (read-eval-print loop)
  • A whole file at a time, in script mode

See Lutz, Chapter 3 or MCS 260 2021 Lec 2.

Variables and types

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.

String features

Strings have useful methods such as .lower(), .startswith(...), .format(...), and many more.

See Lutz, Chapter 7 and MCS 260 Lec 7.

Built-in data structures

  • list - ordered collection of items, access by 0-based index
  • dict - key-value mapping. Given a key, it returns the corresponding value.
  • tuple- like a list, but immutable
  • set - 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 }

See Lutz, Chapter 8 and MCS 260 Lec 5 and Lec 10.

Negative indices and slices

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]

Lists are mutable

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 can be indexed

Strings support some list-like features, such as indexing and slicing.

But unlike lists, strings are immutable.

Membership in dict

If D is a dict, the boolean expression


        x in D
    

checks whether x is a key.

Control structures

Conditionals (if)

Loops (for, while)

(We won't discuss match, which is new in 3.10)

if-elif-else

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
        

Coercion

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.

See Lutz, Chapter 12 and MCS 260 Lec 6 and Lec 18.

Loops

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.

Early exit or resume

break - jump out of the nearest enclosing loop immediately

continue - jump back to the nearest enclosing loop immediately

Files

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.

Functions

Named, reusable code blocks you can call (run) from elsewhere in your code.

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

See Lutz, Chapters 16-18 or MCS 260 Lec 9 and Lec 24.

Docstrings

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.

References

  • Later, I'll post the Python tour notebook I worked on in lecture.
  • Today's slides referenced chapters from Lutz (Learning Python 5ed).
    • UIC students can access the online book for free, but login is required. Instructions on Blackboard.
  • MCS 260 Fall 2021 home page has slide presentations, sample code, and other resources for review.

Revision history

  • 2023-01-11 Finalization of the 2023 lecture this was based on.
  • 2024-01-10 Initial publication.