What will the following code snippet print?
def my_func(my_dictionary):
output = []
for item in my_dictionary:
value = my_dictionary[item]
output.append(value) #append method adds an item to end of a list
return output
# create dictionary and execute function
dictionary = {'first' : 1, 'second' : 2, 'third' : 3}
out = my_func(dictionary)
print(out)
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 `append` method, defined on lists
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
The method append()
is called directly on the list my_list
# append is a method for lists
# this will error with a string
my_string = 'cogs18'
my_string.append('!')
# The `is_integer()` method, defined on floats
my_float = 12.2
my_float.is_integer()
# The `is_integer()` method, attempted on an integer
# this code will produce an error
my_int = 12
my_int.is_integer()
# Make a string all lower case
'aBc'.lower()
# Make a string all upper case
'aBc'.upper()
# Capitalize a string
'python is great'.capitalize()
# Find the index of where a string starts
'Hello, my name is'.find('name')
What will the following code snippet print out?
inputs = ['fIx', 'tYpiNg', 'lIkE', 'tHiS']
output = ''
for element in inputs:
output = output + element.lower() + ' '
output.capitalize()
# sort sorts integers in numerical orders
ints = [16, 88, 33, 40]
ints.sort()
ints
ints.sort(reverse=True)
ints
# append adds to the end of a list
ints.append(2)
ints
# remove value from list
ints.remove(40)
ints
list.remove?
# reverse order of list
ints.reverse()
ints
What will the following code snippet print out?
list_string = ['a', 'c', 'd', 'b']
list_string.sort()
list_string.reverse()
list_string
car = {
"brand": "BMW",
"model": "M5",
"year": 2019
}
# keys() returns the keys of a dictionary
car.keys()
# get returns the value of a specified key
mod = car.get('model')
# equivalent
mod2 = car['model']
print(mod)
print(mod2)
# previously done this by indexing
print(car['model'])
# update adds a key-value pair
car.update({"color": "Black"})
print(car)
Assuming dictionary
is a dictionary that exists, what would the following accomplish:
dictionary.get('letter')
dictionary
dictionary
dictionary
dictionary
Which method would you use to add a new key-value pair to a dictionary?
.append()
.get()
.keys()
.update()
# Reverse a list
my_list = ['a', 'b', 'c']
my_list.reverse()
print(my_list)
# Sort a list
my_numbers = [13, 3, -1]
my_numbers.sort()
print(my_numbers)
car
# Return the keys in the dictionary
out = car.keys()
# print keys
print(type(out))
print(out)
# car has not changed
print(type(car))
print(car)
# Return the values in the dicionary
car.values()
Typing the object/variable name you want to find methods for followed by a '.' and then pressing tab will display all the methods available for that type of object.
# Define a test string
my_string = 'Python'
# See all the available methods on an object with tab complete
my_string.
Using the function dir()
returns all methods available
# For our purposes now, you can ignore any leading underscores (these are special methods)
dir(my_string)
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.
Additional notes included here to remind you of points we've already discussed. Not presented in class, but feel free to review and gain additional clarificaiton.
def
defines a functionfunction_name()
- parentheses are required to execute a functionfunction_name(input1)
- input parameters are specified within the function parenthesesfunction_name(input1, input2)
- functions can take multiple parameters as inputsinput1
and input2
can then be used within your function when it executesreturn
statementIf you write a function called is_odd()
which takes an input value
,
def is_odd(value):
if value % 2 != 0:
answer = True
else:
answer = False
return answer
to use that function, you would execute is_odd(value)
....something like is_odd(value = 6)
out = is_odd(6)
out
Later on, if you wanted to use that function within another function you still have to pass an input to the function.
def new_function(my_list):
output = []
for val in my_list:
if is_odd(val):
output.append('yay!')
return output
new_function([1,2,3,4])
sort_array
¶A version of a selection sort:
def sort_array(array_to_sort):
"""A function to sort an array."""
is_sorted = False # Keeps track of when we are done sorting
sorted_array = [] # A new list that we will use to
while not is_sorted:
lowest = None
for item in array_to_sort:
if lowest == None: # If not defined (first element) set the current element as lowest
lowest = item
if item < lowest:
lowest = items
# these next two lines uses some new (to us) list methods
sorted_array.append(lowest) # Add the lowest value to our sorted array output
array_to_sort.remove(lowest) # Drop the now sorted value from the original array
if len(array_to_sort) == 0: # When `array_to_sort` is empty, we are done sorting
is_sorted = True
return sorted_array
sort_array
¶# Sort an array of integers
unsorted_array = [12, 7, 19, 12, 25]
sorted_array = sort_array(unsorted_array)
print(sorted_array)
# Sort an array of floats
unsorted_array = [21.3, 56.7, 2.3, 2.9, 99.9]
sorted_array = sort_array(unsorted_array)
print(sorted_array)
sorted
¶# Sort a list, with `sorted`
data = [7, 4, 6]
sorted(data)
# what about a list of strings?
sorted(['asdf','abcd'])
# Sort different data types
print(sorted(['a', 'c', 'b']))
print(sorted([True, False, True]))
print(sorted([[1, 4], [1, 2]]))