Python 3

home

Python Intermediate Features

The Introduction to Python course that many of you have taken focused on core features that were considered essential to performing core tasks. However there were a number of features that are still considered "introductory", but were deliberately omitted to help maintain focus on these core features. This slide deck is devoted to bringing you up to speed on these basic features.





dict .get()

Safely get a value from a dictionary without raising a KeyError if the key doesn’t exist.


The .get() method returns the value for a given key in a dictionary. If the key is not found, it returns a default value (or None if no default is given) instead of raising an error.

data = {"a": 1, "b": 2}

val1 = data.get("a")        # int, 1
val2 = data.get("c")        # None
val3 = data.get("c", 0)     # int, 0

We use `.get()` when we want to access dictionary values safely without risking a `KeyError`. It's especially useful when working with user input, optional keys, or data from external sources like APIs.





dict .items()

Retrieve all key-value pairs from a dictionary as (key, value) tuples for iteration or inspection.


The .items() method returns a view of a dictionary’s key-value pairs. Each pair is returned as a tuple.

data = {"a": 1, "b": 2}

for key, value in data.items():
    print(key, value)             # a 1
                                  # b 2

We use .items() when we want to loop through both keys and values in a dictionary at the same time. It's commonly used in for loops to process each entry efficiently.





The 'with' context with objects

Ensure proper acquisition and release of resources, like files or network connections.


The with statement in Python is used to automatically close a file. The file object is actually programmed to close itself as soon as execution leaves the with block.

with open("file.csv", "r") as fh:
    for line in fh:
        print(line)

We use with to automatically handle opening and closing resources, even if an error occurs during use. This makes code cleaner and less error-prone.


with is especially helpful when working with database connections. Database connections are important to release quickly, because they are often shared and in short supply.

import sqlite3

with sqlite3.connect("example.db") as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")

As with the file, the connection object conn is programmed to closed automatically when exiting the block ends, even if an error occurs.





range()

Generate a sequence of integers for iteration, usually in loops.


range() generates a sequence of numbers, often used in for loops.

for i in range(3):
    print(i)           # 0
                       # 1
                       # 2

You can also use the list() function to preserve the numbers:

nums = list(range(3))  # [0, 1, 2]

The range of numbers doesn't need to start at 0:

for i in range(1, 5):
    print(i)            # 1
                        # 2
                        # 3
                        # 4

Note that the upper bound is non-inclusive, the same as with list slices.


A third argument, the step, allows for 'skipping' of nubmers through the count:

for i in range(1, 11, 3):
    print(i)               # 1
                           # 4
                           # 7
                           $ 10




enumerate()

Loop over an iterable while keeping track of the index automatically.


enumerate() adds a counter to an iterable and returns each item as (index, value) pairs. It’s often used in loops when both item and position are needed.

items = ["a", "b", "c"]

for index, value in enumerate(items):
    print(index, value)                # 0 a
                                       # 1 b
                                       # 2 c

We use enumerate() to avoid manually tracking indexes when looping. It keeps code cleaner and less error-prone.


enumerate() can be usefully used with a file, to number the lines:

with open("example.txt", "r") as f:
    for line_num, line in enumerate(f, start=1):
        print(f"{line_num}: {line.strip()}")

Note the start=1 argument, which starts the counting at a number of your choice.





The date, datetime and timedelta objects

Date calculations are easily managed with these objects.


The date object represents a date.

from datetime import date, timedelta

today = date.today()           # date object representing today (2025-03-26)
three_days = timedelta(days=3)

then = today + three_days

print(then)                    # date(2025, 3, 29)

This can help with calculations that may be a bit more complex - handling whether months have 28, 29, 30 or 31 days.


The datetime object represents a date and time.

now = datetime.now()     # datetime object representing now (2025-03-26 5:56pm)

tomorrow = today + timedelta(days=1, hours=2)

print(tomorrow)          # datetime(2025, 03, 27, 7:56pm)

Possible arguments for timedelta():


All are optional and default to 0. You can combine them as needed.





[pr]