1 of 18

Bonus Python

Winter 2025

1

Adrian Salguero

2 of 18

Announcements

  • Homework 6 is due Friday, March 14th by 11:59pm
    • No extensions or resubmissions will be allowed
  • Coding Practice 8 is due Wednesday, March 12th by 11:59pm
  • Fill out Course Evaluation for the course
    • Due by Sunday, March 16th at 11:59pm
  • Final Exam is on Thursday March 20th at 2:30pm
    • DRS students - register with DRC Testing Center

2

3 of 18

Python Topics for Today

  • List comprehensions
  • Enumerate a list
  • Ternary assignment
  • Raising and catching errors

NOTE: None of this material will appear on the Final Exam!

3

4 of 18

List Comprehensions

  • Shorter syntactical way to create a new list

list = [expression for item in iterable <if condition == True>]

4

5 of 18

Examples of List Comprehension

list = [x for x in range(4)]

[0, 1, 2, 3]

list = [x for x in range(4) if x%2 == 0]

[0, 2]

names = [“Vibhav”, “John”, “Suh Young”]

list = [len(x) for x in names]

[6, 4, 9]

5

6 of 18

Enumerate a list

Suppose we have the following list:

lst = [10 ** x for x in range (10)]

We can print the values and corresponding index as so:

for i in range(len(lst)):

print(‘value at index’, i, ‘is’, lst[i])

Or we can use the built-in enumerate function:

for index, value in enumerate(lst):

print(‘value at index’, index, ‘is’, value)

6

7 of 18

Enumerate

  • Iterating through an enumerate object will print out tuples of the form(index, value)

lst = [100, 200, 300, 400, 500]

for x in enumerate(lst):

print(x)

(0, 100)

(1, 200)

(2, 300)

(3, 400)

(4, 500)

7

8 of 18

Practice: Enumerate a list

Goal: Write code that creates a list where each element is the sum of the element and it’s index

Without list comprehension or enumerate:

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

new_lst = [ ]

for i in range(len(lst)):

new_lst.append(i + lst[i])

8

9 of 18

Practice: Enumerate a list

Goal: Write code that creates a list where each element is the sum of the element and it’s index

With list comprehension and enumerate:

lst = [x for x in range(10)]

new_lst = [i + v for i,v in enumerate(lst)]

9

10 of 18

Practice Problem: Enumerate

Given a list of participants, in the order they finished a race, create a dictionary that maps their name to their finishing place.

Input

racers = [‘Dino’, ‘Wilma’, ‘Barney’, ‘Fred’]

Output

race_dict = {‘Dino’: 1, ‘Wilma’: 2, ‘Barney’: 3, ‘Fred’: 4}

10

11 of 18

Ternary Assignment

A common pattern in Python code

if x > threshold:

flag = “Over”

else:

flag = “Under”

With a ternary expression

flag = “Over” if x > threshold else “Under”

11

12 of 18

Other Forms of Ternary Assignments

If-elif-else:

if temperature > 90:

weather = “Hot”

elif temperature < 40:

weather = “Cold”

else:

weather = “Mild”

With ternary assignments

weather = “Hot” if temperature > 90 else “Cold” if temperature < 40 else “Mild”

12

13 of 18

Other Forms of Ternary Assignments

With Tuples:

flag = (“Negative”, “Positive”)[x >= 0]

With Dictionaries:

flag = {True: “Positive”, False: “Negative”} [x >= 0]

13

14 of 18

Other Forms of Ternary Assignments

With Tuples:

flag = (false_value, true_value)[x >= 0]

With Dictionaries:

flag = {True: true_value, False: false_value} [x >= 0]

14

15 of 18

Raising (“Throwing”) Errors

  • Suppose you want to raise (or throw) an error in your function in the case that a user incorrectly uses the function.

def always_raises_error():

raise ValueError(“This is a value error!”)

15

16 of 18

Catching Errors

  • You can also “catch” and error and provide additional information about the error.

def always_raises_error():

raise ValueError(“This is a value error!”)

try:

always_raises_error()

except ValueError:

print(“Please don’t call this function!”)

16

17 of 18

Trying and Catching IndexOutOfBounds

def print_val_at_index(lst, index):

try:

lst[index]

except IndexError:

print("Index out of bounds!")

else:

print(lst[index])

17

18 of 18

Common Errors

  • IndexError – Index out of range
  • KeyError – Key not found in dictionary
  • IndentationError – Invalid indentation
  • TypeError – Operation applied to invalid combination of types
  • ValueError – Function gets properly typed argument, but invalid value
  • SyntaxError – Invalid Python syntax
  • NameError – Variable name not found
  • FloatingPointError – Floating point operation fails
  • RuntimeError – Otherwise Unknown Error

18