tuples, dicts and exception handling

29
Tuples, Dicts and Exceptions Python SIG – PYA Class 4 – 3/10/15

Upload: pranavsb

Post on 22-Jan-2017

146 views

Category:

Software


6 download

TRANSCRIPT

Page 1: Tuples, Dicts and Exception Handling

Tuples, Dicts and Exceptions

Python SIG – PYA Class 4 – 3/10/15

Page 2: Tuples, Dicts and Exception Handling

(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

Page 3: Tuples, Dicts and Exception Handling

(Revision of) How import works

• .py and .pyc files• sys.path• if __name__ == ‘__main__’

Page 4: Tuples, Dicts and Exception Handling

(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()

Page 5: Tuples, Dicts and Exception Handling

(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()

Page 6: Tuples, Dicts and Exception Handling

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?

Page 7: Tuples, Dicts and Exception Handling

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

Page 8: Tuples, Dicts and Exception Handling

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]

Page 9: Tuples, Dicts and Exception Handling

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()

Page 10: Tuples, Dicts and Exception Handling

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’}

Page 11: Tuples, Dicts and Exception Handling

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

Page 12: Tuples, Dicts and Exception Handling

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()

Page 13: Tuples, Dicts and Exception Handling

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.

Page 14: Tuples, Dicts and Exception Handling

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?

Page 15: Tuples, Dicts and Exception Handling

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

Page 16: Tuples, Dicts and Exception Handling

Exception Handling[4] -Because errors are bad!

Page 17: Tuples, Dicts and Exception Handling

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]

Page 18: Tuples, Dicts and Exception Handling

try except

try:#potentially dangerous code

except:pass

Even though there is a pass, it is useful

Page 19: Tuples, Dicts and Exception Handling

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

Page 20: Tuples, Dicts and Exception Handling

try except

try:#potentially dangerous code

except TypeError:print 'type'

except KeyError:print 'key'

Page 21: Tuples, Dicts and Exception Handling

try except

try:#potentially dangerous code

except (TypeError, KeyError):print 'type or key'

Page 22: Tuples, Dicts and Exception Handling

try except

try:#potentially dangerous code

except TypeError, err_info:print 'type‘, str(err_info)

Page 23: Tuples, Dicts and Exception Handling

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.

Page 24: Tuples, Dicts and Exception Handling

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

Page 25: Tuples, Dicts and Exception Handling

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

Page 26: Tuples, Dicts and Exception Handling

with

• Mainly used for file r/w operations• Alternative to try except in these cases• with open(‘filename.txt’) as f1:

f1.close()

Page 27: Tuples, Dicts and Exception Handling

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.

Page 28: Tuples, Dicts and Exception Handling

Thanks!

Pranav S Bijapur, ECE, BMSCE, Bangalore

[email protected] Telegram - @pranavsb

Page 29: Tuples, Dicts and Exception Handling

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/