Methods#

Q&A

Q: Is break only used in debugging code, or is there a practical application where we’d use it in a loop other than that?
A: Any time where you want the loop to end after the first time you encounter something, break can be helpful!

Q: Difference between append and +=
A: append can only be used to add something to the end of a list. += can be used to concatenate strings or add a number to a numeric type variable

Course Announcements

Due this week:

  • VQ10 due Wed

  • CL5 due Fri

  • Mid-course survey “due” (for extra credit) Sunday - link also on Canvas assignment

Notes:

  • A4 now available - we’re just starting this material; due next Sun

  • Attendance in lab and TA office hours is low - go if you’re struggling!

  • Really watch and pay attention to videos for VQ10 (please)!

Exam Summary

  • Well done, overall!

  • Mean: 86%

  • Perfect scores: 8%!

  • Average/Median Duration: 33min

  • Students can re-take E1 this week; sign up in PrairieTest

Methods#

  • string, list, & dictionary

  • in place vs not in place

  • relationship to functions

…and input() + try/except

Methods#

Methods are functions that are defined and called directly on an object.
For our purposes, objects are any data variable.

Method Examples#

A method is a function applied directly to the object you call it on.

General form of a method:

object.method()

In other words: methods “belong to” an object.

The method append() is called directly on the list my_list

# The `append` method, defined on lists
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
[1, 2, 3, 4]
# append is a method for lists
# this will error with a string
my_string = 'cogs18'
my_string.append('!')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[2], line 4
      1 # append is a method for lists
      2 # this will error with a string
      3 my_string = 'cogs18'
----> 4 my_string.append('!')

AttributeError: 'str' object has no attribute 'append'

Available methods:#

Methods: In Place vs Not In Place#

Some methods update the object directly (in place), whereas others return an updated version of the input.

List methods that are in place#

# Reverse a list
my_list = ['a', 'b', 'c']
my_list.reverse()

print(my_list)
['c', 'b', 'a']
# Sort a list
my_numbers = [13, 3, -1]
my_numbers.sort()

print(my_numbers)
[-1, 3, 13]

Dictionary methods that are not in place#

car = {'make': 'Hyundai',
       'model': 'Santa Fe',
       'year': 2009}
# Return the keys in the dictionary
out = car.keys() 
out
dict_keys(['make', 'model', 'year'])
# car has not changed
car
{'make': 'Hyundai', 'model': 'Santa Fe', 'year': 2009}
# Return the values in the dicionary
car.values()
dict_values(['Hyundai', 'Santa Fe', 2009])
# string methods operate NOT in place
my_string = 'hello'
new_string = my_string.upper()
new_string
'HELLO'
my_string
'hello'

Correspondance Between Functions & Methods#

All methods are functions. Methods are special functions attached to a variable type. All functions are NOT methods.

Note that:

my_variable.function_call()

acts like:

function_call(my_variable)

A function that we can call directly on a variable (a method) acts like a shortcut for passing that variable into a function.

Activity: Methods#

Please complete the two questions here: https://forms.gle/Rbs92oSbiRzdET4p8. For these, best to read the code and think before trying the code out and getting the answer.

You are encouraged to:

  • talk to one another!

  • ask each other questions

  • ask me questions

inputs = ['fIx', 'tYpiNg', 'lIkE', 'tHiS']
output = ''

for element in inputs:
    output = output + element.lower() + ' '

output.capitalize()
'Fix typing like this '

.items(): Using dictionary methods…to loop#

# defined earlier in notes
car
{'make': 'Hyundai', 'model': 'Santa Fe', 'year': 2009}
car.items()
dict_items([('make', 'Hyundai'), ('model', 'Santa Fe'), ('year', 2009)])
for key, value in car.items():
    print('key: ', key)
    print('value: ', value)
key:  make
value:  Hyundai
key:  model
value:  Santa Fe
key:  year
value:  2009

Activity: .items()#

Include your code for this question in this form: https://forms.gle/yG8AmpMDs5BUCHUh9

Can you re-write this function (accomplishing the same task!) using .items():

def passing_students(scores_dict, passing_score):
    passed_students = []
    
    for student in scores_dict:
        if scores_dict[student] >= passing_score:
            passed_students.append(student)

    return passed_students

Notes:

  • We initially drafted some of this code in the Loops notes.

  • Including students below so you don’t have to type out a dictionary with students’ names and scores

# CODE
def passing_students(scores_dict, passing_score):
    passed_students = []
    
    for student, score in scores_dict.items():
        if score >= passing_score:
            passed_students.append(student)

    return passed_students
# a dictionary to help you test things out...
students = {
    'Alondra': 85,
    'Holly': 58,
    'Brooke': 92,
    'Pauline': 47,
    'Minqi': 76
}
more_students = {
    'Alondra': 85,
    'Holly': 58,
    'Brooke': 92,
    'Pauline': 47,
    'Minqi': 76,
    'Kayden': 88, 
    'Kaia' : 55,
    'Yueyan' : 90
}
# TRY IT OUT
passing_students(students, 70)
['Alondra', 'Brooke', 'Minqi']
passing_students(more_students, 70)
['Alondra', 'Brooke', 'Minqi', 'Kayden', 'Yueyan']

input()#

  • allows you to get input from a user

  • can store it in a variable

  • will store it as a string

input()
my_value = input()

try/except#

What if you want Python to try to run some code…but do something else if it encounters an exception?

def get_an_input_integer():
    in_string = input('Enter your favorite whole number:\n')

    try:
        in_integer = int(in_string)
    except:
        in_integer = None
        
    return in_integer
get_an_input_integer()

Going Deeper: What would this look like without a try/except?

def get_an_input_integer_wo():
    in_string = input('Enter your favorite whole number:\n')
    in_integer = int(in_string)
    return in_integer
get_an_input_integer_wo()

Think-Pair-Share#

How do these (try/except) differ from a conditional?

# if you want to test some ideas out...

Where are we going?#

class - creating our own object types!

  • attributes

  • methods <- we know what these are now!