Download - Tuples, Dicts and Exception Handling
Tuples, Dicts and Exceptions
Python SIG – PYA Class 4 – 3/10/15
(Revision of) Functions
• def func_name(params = default):# codereturn something, something_else
• Order of execution – better to make module sometimes
• Docstrings• global statement and global variables
(Revision of) How import works
• .py and .pyc files• sys.path• if __name__ == ‘__main__’
(Revision of) List methods[1]
• Do dir([]) and try to guess what each of the methods might do to a list.
• list.append(element)• list.extend(list)• list.remove(element)• list.pop(index)• list.reverse()• list.sort()
(Revision of) String methods[1]
• Do dir(‘’) and try to guess what each of methods might do to a string. (Fairly obvious)
• string.split(delimiter)• string.upper() / .lower()• ‘ ‘.join([list of things to join])• string.startswith() / .endswith()
Tuples
• Tuples are “immutable lists”• tuple1 = (‘a’, 1, [1,2])• dir(some_tuple) returns only “count” and
“index” (apart from double underscore methods)
• Check help(‘tuple.count’) and help(‘tuple.index’)
• Why use them then?
Why Tuples?
• Because they are faster than lists• Because you may want something to be fixed
in value• You can slice, and (negative) index tuples, like
lists• You can use ‘in’ to see if a tuple contains a
particular element
Tuples
• A tuple is not ‘()’ it is ‘,’• ‘It makes your code safer if you “write-
protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that shows this data is constant, and that special thought (and a specific function) is required to override that.’ – Dive Into Python[2]
Tuples
• How to create a tuple with a single element?• (Parentheses don’t matter to a tuple.)• You can convert a list to a tuple and vice versa
with tuple() and list()
Dictionaries
• key – value pairs• keys have to be immutable• values don’t• More complex data structure• Many use cases possible• dict1 = { 1:’a’, 2:’b’, 3:’c’}
Dictionaries
• dict methods – mainly .keys(), .values() and .items()
• They return a list, list and list of tuples repectively
• If d1 is a dictionary, what will ‘for i in d1: print i’ print?
• dict[valid_key] = corresponding_value• dict[invalid_key] gives a KeyError
Dictionaries
• .get(key, default_value) when we don’t want the program crashing because of KeyErrors
• .keys() won’t return alphabetically sorted list• Can use sorted() or .sort()
Assignment
• Make your own module. Write a program that contains a function and define some variables. Import that into another program and make sure it is able to access the functions and variables of the imported file.
Assignment
• Make a telephone directory which maps a last name and a first name to a phone number. It should contain a few names and prompt the user for 3 more. Finally, try to sort the names alphabetically and display them to the user.
• Is the first dictionary sorted?• Can you use a second dictionary?
Assignment
• Write a program to display the number of times a particular alphabet appears in a string.
• For example ‘aabbBc’ should return a was present 2 timesb was present 2 timesB was present 1 timec was present 1 time
Exception Handling[4] -Because errors are bad!
Exception Handling
• Say files not found or importing of libraries failed
• “Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages.”[3]
try except
try:#potentially dangerous code
except:pass
Even though there is a pass, it is useful
try except
• try... except vs. try... except Exception• The first one will also catch KeyboardInterrupt
etc• See Stack Oveflow answer by vartec:– https://stackoverflow.com/questions/730764/try-
except-in-python-how-do-you-properly-ignore-exceptions
try except
try:#potentially dangerous code
except TypeError:print 'type'
except KeyError:print 'key'
try except
try:#potentially dangerous code
except (TypeError, KeyError):print 'type or key'
try except
try:#potentially dangerous code
except TypeError, err_info:print 'type‘, str(err_info)
try except else finally
• The else block is executed when no error is caught.
• The finally block is executed no matter what.• What if the except block has an error?• Used for clean-up code, like closing files.
assert
• assert condition, “Something went wrong.”• If condition evaluates to False, an
AssertionError occurs• To make program “fail fast”• You’ll know where it happened• assert has been used before
raise
• raise Exception(“Error!”)• Again, “fail fast”• Can replace error description with our own• A list of exceptions can be found on the online
documentation – https://docs.python.org/2/library/exceptions.html
with
• Mainly used for file r/w operations• Alternative to try except in these cases• with open(‘filename.txt’) as f1:
f1.close()
Assignment
• Make code that can handle all possible exceptions but also gives information to the user on what the exact error was.
• For example, the palindrome checker from last class. Think of all possible errors that can occur.
• Fix your code for today’s previous assignments.
References
1 – Taken from the previous (class 3) lecture2 – Dive Into Python by Mark Pilgrim 3 – Python online docshttps://docs.python.org/2/tutorial/errors.html4 – xkcd comic – goto
https://xkcd.com/292/