Lecture 8: A cure for what ails you

Size: px
Start display at page:

Download "Lecture 8: A cure for what ails you"

Transcription

1 Lecture 8: A cure for what ails you

2

3 When human beings acquired language, we learned not just how to listen but how to speak. When we gained literacy, we learned not just how to read but how to write. And as we move into an increasingly digital reality, we must learn not just how to use programs but how to make them. In the emerging, highly programmed landscape ahead, you will either create the software or you will be the software. It s really that simple: Program, or be programmed. Choose the former, and you gain access to the control panel of civilization.choose the latter, and it could be the last real choice you get to make.

4 Today Today we ll start by having a look at functions -- Next time we will finish off the last dangling Python thread, user-defined objects We ll then cover some coding strategies in Python to deal with uncertainties as well as a simple Python debugger to assess the operation of your running code We will then spend some time with MongoDB, an option we will revisit later in the quarter but one that some of you may be interested in for your project -- We ll close with your next homework assignment!

5 Functions As you ve probably seen with this homework, the more you build with Python, the more difficult it becomes to effectively create/maintain/share your code as one single piece (whether that be a script or a module) You are inevitably led to breaking up computations into smaller units; and, as with R, a function is Python s way of letting you group statements that can be repeated elsewhere in your program With that in mind, you should anticipate that the specification for a function will need to define the group of statements you want to consider; specify the variables you want to involve in your computation; and return a result

6 Function definition As we saw last time, functions are created with the def statement; it defines another block of code that makes up the function s body (either an intended set of statements or a simple statement after the colon) The def statement is a kind of assignment in that it associates the function s name with an object of type funct; the def statement can occur anywhere (well, anywhere a statement can) and the named functions are defined at runtime (meaning the function is created when you execute your code) Let s see how this works...

7 >>> from random import normalvariate, lognormvariate >>> def noise(x): # defining functions... return x+normalvariate(0,1)... >>> noise(3) >>> type(noise) # noise points to an object of type 'function' <type 'function'> >>> clatter = noise >>> clatter(2) >>> if wild:... def noise(x):... 'log-normal noise'... return x+lognormvariate(0,1)... else:... def noise(x):... 'gaussian noise'... return x+normalvariate(0,1)... >>> noise(5) >>> help(noise)

8 Identifying data to compute with So that example seemed pretty straightforward; we had a single argument and assigned it a value when we called the function But almost immediately subtleties arise, and we have to ask questions about how this assignment is done and how, in general, Python treats variables in the body of a function

9 Scoping rules (again) As we will see with R, when we use a name in a program (in an assignment or a simple expression, say), Python needs to associate that name with some object The visibility of a name within our program is determined by where it s assigned (literally the location of the assignment statement in our code); this visibility is referred to as a name s scope To talk about scope and the process that Python uses to associate names with objects, we need to revisit the concept of a namespace; but first some examples...

10 >>> from random import normalvariate, lognormvariate >>> >>> def noise(x):... z = 5 # y,z are local variables; they exist within a... y = x+normalvariate(z,1) # namespace created when noise is executed... return y... >>> noise(3) >>> z # but we can t find z outside of the body of noise Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'z' is not defined >>> >>> def noise(x): # let s create another version of noise, this time... y = x+normalvariate(z,1) # removing the definition of z... return y... >>> noise(3) # oops! Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in noise NameError: global name 'z' is not defined >>> z = 10 # now let s create a variable named z >>> noise(3) # where is python finding it? >>> y = 1 >>> noise(3) >>> y 1

11 Scoping rules When we first started writing Python code, all our variable assignments took place at the top level of a module*; that is, their names were part of the module s namespace, or the global scope of the module and we could refer to them simply Notice that this sense of global is really file-based; that is, when we write a module, we don t have to worry about whether someone using our module has defined variables of the same name in their code With functions, we introduce a nested namespace (a nested scope) that localizes the names they use so that you can avoid similar kinds of clashes * If it is typed in at the >>> prompt, you are in a module called main ; otherwise the enclosing module is the file that contains your program

12 Scoping rules The execution of a function introduces a new namespace for the local variables of the function; all variable assignments in a function store their names in this local namespace When we look up variable name (by referring to it in an expression in the function, say), Python first looks in this local namespace; if it can t find an object of that name locally, it starts a search that moves out to (eventually) the global namespace and then the collection of built-in names During this lookup process, Python will return the object associated with the first instance of the name it finds; so local names take precedence over globals Also, the names associated with a function s namespace are determined when its definition is executed; they are treated as locals everywhere in the function, not just after the statements where they are assigned...

13 >>> # built-in scope >>> import builtin >>> dir( builtin ) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', ' debug ', ' doc ', ' import ', ' name ', ' package ', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

14 >>> from random import normalvariate, lognormvariate >>> y = 10 >>> def noise(x): print y # y is not defined in the local namespace... >>> noise(3) 10 >>> def noise(x):... print y... y = x+normalvariate(0,1) # y is defined in the local namespace, but only... return y # assigned after the print statement, hence the error... >>> noise(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in noise UnboundLocalError: local variable 'y' referenced before assignment

15 Scoping rules Because def is a statement like any other, we can certainly define functions within other functions; in that case, our search for variables works way out through the enclosing functions Lutz defines the LEGB rule for resolving a name: When a name is referenced, Python will look it up in the following order: 1. The Local (function) scope 2. The Enclosing function scope 3. The Global (module) scope, and 4. The Built-in scope

16 Passing arguments The names in your argument list become new local names (local variables) and arguments are passed to a function by assigning objects to local names; that means the variable names in the argument list are assigned references to the objects you specify (this is VERY different from what you will see in R) For immutable objects like numbers or strings, this is safe enough (remember, Python makes copies of immutable objects when you start to work with them); for mutable objects like lists and dictionaries, this can produce some unexpected consequences...

17 >>> from random import normalvariate, lognormvariate >>> # now let's try passing a mutable object >>> def vnoise(x): # a vector version... y = [a+normalvariate(0,1) for a in x]... return y... >>> >>> x = range(5) >>> vnoise(x) [ , , , , ] >>> >>> def vnoise(x):... y = [a+normalvariate(0,1) for a in x]... x[1] = "YIKES"... return y... >>> vnoise(x) [ , , , , ] >>> x [0, 'YIKES', 2, 3, 4]

18 Passing arguments With unexpected consequences like these, it s important to adopt a good coding style; you probably want to avoid having functions change global variables (people hate unexpected surprises) -- In coding parlance, things like YIKES are known as side effects and R, for example, strives to minimize these Remember, good coding practice is as much about readability and reliability as it is about efficiency...

19 Argument matching Often, we want to include default values for some of the arguments of our function; these can be convenient and might also serve a kind of documentation service In general, our function definition can include both non-keyword as well as keyword arguments, separated into two groups, with non-keyword coming first In R, we will see a detailed process whereby arguments were assigned values in a given function call -- Python takes a simpler, constrained approach, throwing an error if you break the rules When we call a function in Python, you are to first specify values for your nonkeyword arguments followed by some collection of your keyword arguments (in any order) -- Python also allows for the equivalent of..., but uses separate lists for the keyword and non-keyword arguments

20 >>> from random import normalvariate, lognormvariate >>> def noise(x,mu=0,sig=1):... y = x+normalvariate(mu,sig)... return y... >>> noise(3,5,1) # call by position >>> noise(x=3,sig=1,mu=5) # call by name >>> noise(3,sig=2) # using defaults >>> >>> def noise(x,*junk,**named_junk): # the ** catches named things in a dictionary... print "junk: ", junk # the * catches unnamed things in a list... print "junk: ",type(junk)... print "junk: ",named_junk... print "junk: ",type(named_junk)... return normalvariate(0,1)... >>> noise(3,17,5,w="hi",z="low") junk: (17, 5) junk: <type 'tuple'> junk: {'z': 'low', 'w': 'hi'} junk: <type 'dict'>

21 Catching the result Finally, all of the functions we ve defined today explicitly return something with a return statement -- When a return statement is not present, the function will instead return the value None after it has completed its computation Recall that None is an object with type NoneType and will evaluate to False

22 Double duty With a simple device, we can have some code we have created act either as a module (sharing computations) and a standalone program cocteau@homework:~$ cat some_math.py #!/usr/local/bin/python def square(x): return x*x if name == ' main ': print "test: square(35) = ",square(35) cocteau@homework:~$ python some_math.py test: square(35) = 1225 cocteau@homework:~$ python Python 2.7 (r27:82500, Oct , 16:27:47) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import some_math >>> some_math.square(5) 25

23 Behind the scenes While we re here, it s worth commenting on what Python is doing when you execute a file -- There are a few basic steps before it starts working on your tasks 1. Byte code compilation: Python translates your source code into another format known as byte code, a platform independent translation to byte code instructions 2. PVM: Once byte compiled, your code is then handed over to the Python virtual machine (PVM), the Python runtime engine; this is where your code is actually executed

24 cp /data/text_examples/some_math.py. ls some_math* some_math.py python Python 2.7 (r27:82500, Oct , 16:27:47) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import some_math >>> type(some_math.square) <type 'function'> >>> some_math.square(5) 25 >>> ^D ls -l some_math* -rwxr-xr-x 1 cocteau cocteau :31 some_math.py -rw-r--r-- 1 cocteau cocteau :32 some_math.pyc cocteau@homework:~$ hexdump some_math.pyc f303 0a0d 43ad 4cbf b a b e c 7c e c d6f 5f65 616d e a b f5f 616d 6e69 5f5f c a d d e e f00 6e5f 6d f0 5f65 285f c d6f 5f65 616d e d3c 646f 6c75 3e c d

25 Debugging Python has a simple facility (that is reminiscent of many similar tools for other languages) that helps you assess what is going on when you program runs -- By now you ve had the experience of typing commands into the interactive shell, then collecting them into a file and executing a program Inevitably, as you work with that program, some program, you ll come across conditions that cause your computations to fail in some way -- Even if you re very careful, code that you take from others may not be crafted with the same level of caution Of course a simple approach to debugging is to just insert print statements everywhere in your code -- I ll admit it, sometimes you ll catch me doing this depending on the complexity of the task

26 Debugging Python s built-in debugger, PDB provides us a more formal technique for investigating a running program -- PDB creates (yet another) shell with its own commands for working with lines of code b ( break ) to set a breakpoint cl ( clear ) a breakpoint tbreak to set a one-time breakpoint ignore to specify that a certain breakpoint will be ignored the next k times, where k is specified in the command l ( list ) to list some lines of source code n ( next ) to step to the next line, not stopping in function code if the current line is a function call s ( subroutine ) same as n, except that the function is entered in the case of a call c ( continue ) to continue until the next break point w ( where ) to get a stack report u ( up ) to move up a level in the stack, e.g. to query a local variable there d ( down ) to move down a level in the stack r ( return ) continue execution until the current function returns j ( jump ) to jump to another line without the intervening code being executed h ( help ) to get (minimal) online help (e.g. h b to get help on the b command, and simply h to get a list of all commands); type h pdb to get a tutorial on PDB31 q ( quit ) to exit PDB

27 cp /data/text_examples/debug_test.py. /usr/local/lib/python2.7/pdb.py debug_test.py > /home/cocteau/test.py(5)<module>() -> import re (Pdb) l 1! #!/usr/local/bin/python 2! 3! #import pdb 4! 5 ->! import re 6! from BeautifulSoup import BeautifulStoneSoup 7! 8! recipe_file = "/data/text_examples/1985/01/02/ sgml" 9! bs = BeautifulStoneSoup(open(recipe_file)) 10! 11! #pdb.set_trace() (Pdb) n > /home/cocteau/test.py(6)<module>() -> from BeautifulSoup import BeautifulStoneSoup (Pdb) n > /home/cocteau/test.py(8)<module>() -> recipe_file = "/data/text_examples/1985/01/02/ sgml" (Pdb) n > /home/cocteau/test.py(9)<module>() -> bs = BeautifulStoneSoup(open(recipe_file)) (Pdb) p recipe_file '/data/text_examples/1985/01/02/ sgml' (Pdb) l 4! 5! import re 6! from BeautifulSoup import BeautifulStoneSoup 7! 8! recipe_file = "/data/text_examples/1985/01/02/ sgml" 9 ->! bs = BeautifulStoneSoup(open(recipe_file)) 10! 11! #pdb.set_trace() 12! 13! word_count = 0 14!

28 (Pdb) l 20 15! for p in bs.findall("p"): 16! 17! line = p.gettext() 18! line = re.sub("\s+"," ",line) 19! line = line.strip() 20! line = line.lower() 21! 22! for w in line.split(" "): 23! 24! w = re.sub("\w","",w) 25! (Pdb) b 24 Breakpoint 1 at /home/cocteau/test.py:24 (Pdb) c > /home/cocteau/test.py(24)<module>() -> w = re.sub("\w","",w) (Pdb) l 19! line = line.strip() 20! line = line.lower() 21! 22! for w in line.split(" "): 23! 24 B->! w = re.sub("\w","",w) 25! 26! if w: 27! 28! word_count += 1 29! print w (Pdb) n > /home/cocteau/test.py(26)<module>() -> if w: (Pdb) p w u'while'

29 (Pdb) c while > /home/cocteau/test.py(24)<module>() -> w = re.sub("\w","",w) (Pdb) n > /home/cocteau/test.py(26)<module>() -> if w: (Pdb) p w u'there' (Pdb) cl 1 Deleted breakpoint 1 (Pdb)!x = "arbitrary python statements prefaced by a!" (Pdb) p x (Pdb) h Documented commands (type help <topic>): ======================================== EOF bt cont enable jump pp run unt a c continue exit l q s until alias cl d h list quit step up args clear debug help n r tbreak w b commands disable ignore next restart u whatis break condition down j p return unalias where Miscellaneous help topics: ========================== exec pdb Undocumented commands: ====================== retval rv (Pdb)

30 Debugging When debugging, one often employs a strategy of divide and conquer -- That is, you first check to see if everything is OK in the first half of your program, and, if so, check the 3/4 point, otherwise check the 1/4 point In short, a debugging program won t tell you what your bug is, but it can help you find out where it is There are various visual or GUI-based extensions to PDB and IPython has a very clean debugger built-in -- This kind of tool can help you scrape through a piece of code more efficiently than the old stand-by of inserting print commands everywhere

31 Programming defensively Python offers a simple construction that allows you to catch errors and handle them in your running code -- Not every error should cause your program to exit, but instead produce fixable situations For example, if we are pulling data from the web, we might occasionally encounter an network error -- In that case we might want to have our program respond by sleeping for a little while and try the access later The try/catch/finally structure allows you trap various kinds of exceptions that are raised while your code executes -- Let s start with a simple arithmetic error

32 >>> x = 5 >>> y = 0 >>> try:... z = x/y... except ZeroDivisionError: # here we are looking for a particular exception... print "divide by zero" divide by zero >>> >>> try:... x/y... except ZeroDivisionError, e: # here we are catching an exception objects... z = e... >>> print z integer division or modulo by zero >>> type(z) <type 'exceptions.zerodivisionerror'> >>> try:... x/y... except: # catch any error... print 'a problem'... else:... print 'it worked!' 'a problem'

33 Programming defensively You can handle exceptions in a nested way, testing for more specific errors first, and ending with the more general -- The finally statement provides code that s executed no matter what happened inside the code blocks try: block-1... except Exception1: handler-1... except Exception2: handler-2... else: else-block finally: final-block You are also able to raise exceptions in your code, allowing your modules to propagate exceptions so that your users can handle them as they see fit

34 Data formats XML is not the only data format out there; and with the advent of client-side tools like JavaScript (a language that runs in your browser and was originally meant to let programmers work with pages displayed by the Netscape Navigator; what kinds of objects might this language expose? What methods?) JSON (JavaScript Object Notation) is billed as a light-weight data-interchange format that is easy for humans to read and write ; why might a program running in your browser need to send and receive data? As a format, JSON uses conventions that are familiar to users of languages like C or, as luck would have it, Python; here s what you get when you request the Twitter public timeline page in JSON* *

35 curl > ptl.json % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed :--:-- --:--:-- --:--: head ptl.json [{"place":null,"contributors":null,"coordinates":null,"truncated":false,"in_reply_ to_screen_name":null,"geo":null,"retweeted":false,"source":"<a href=\" twitterfeed.com\" rel=\"nofollow\">twitterfeed</a>","created_at":"mon Oct 18 21:14: ","in_reply_to_status_id":null,"user": {"geo_enabled":false,"friends_count": 0,"profile_text_color":"333333","description":null,"contributors_enabled":false,"p rofile_background_tile":false,"favourites_count": 0,"profile_link_color":"0084B4","listed_count": 5,"verified":false,"profile_sidebar_fill_color":"DDEEF6","url":null,"follow_reques t_sent":null,"notifications":null,"time_zone":null,"lang":"en","created_at":"tue Jun 08 11:52: ","profile_sidebar_border_color":"C0DEED","profile_image_url":" s.twimg.com/a/ /images/ default_profile_2_normal.png","location":null,"protected":false,"profile_use_backg round_image":true,"screen_name":"2webtraffic","name":"web traffic","show_all_inline_media":false,"following":null,"profile_background_color" :"C0DEED","followers_count":734,"id": ,"statuses_count": 14544,"profile_background_image_url":" themes/theme1/ bg.png","utc_offset":null},"retweet_count":null,"favorited":false,"id": ,"in_reply_to_user_id":null,"text":"How To Get Traffic From Social Networks Social Marketing Tips: Social networking could be defined as an online... {"place":null,"contributors":null,"coordinates":null,"truncated":false,"in_reply_t o_screen_name":null,"geo":null,"retweeted":false,"source":"web","created_at":"mon Oct 18 21:14: ","in_reply_to_status_id":null,"user":{"statuses_count":

36 [ {"place":null, "contributors":null, "coordinates":null, "truncated":false, "in_reply_to_screen_name":null, "geo":null, "retweeted":false, "source":"<a href=\" rel=\"nofollow\">twitterfeed</a>", "created_at":"mon Oct 18 21:14: ", "in_reply_to_status_id":null, "user":{ "geo_enabled":false, "friends_count":0, "profile_text_color":"333333", "description":null, "contributors_enabled":false, "profile_background_tile":false, "favourites_count":0, "profile_link_color":"0084b4", "listed_count":5,... "utc_offset":null}, "retweet_count":null, "favorited":false, "id": , "in_reply_to_user_id":null, "text":"how To Get Traffic From Social Networks Social Marketing Tips: Social networking could be defined as an online... ] Look familiar?

37

38

39 Python - JSON As you might expect, a JSON object has a (relatively) direct translation into Python built-in types (numbers, strings, dictionaries, lists) -- For this reason, it is exceedingly popular as a tool for storing data As we will see in a later lecture, there are also very efficient databases for storing, indexing and retrieving JSON strings -- One such offering is MongoDB, something we ll work with once our recipes are done How might this help us?

40 % curl > ptl.json % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed :--:-- --:--:-- --:--: % python Python 2.7 (r27:82500, Oct , 16:27:47) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import json >>> f = open("ptl.json") >>> tweets = json.loads(f.readline()) >>> type(tweets) <type 'list'> >>> type(tweets[0]) <type 'dict'> >>> tweets[0].keys() ['favorited', 'contributors', 'truncated', 'text', 'created_at', 'retweeted', 'coordinates', 'source', 'in_reply_to_status_id', 'in_reply_to_screen_name', 'user', 'place', 'retweet_count', 'geo', 'id', 'in_reply_to_user_id'] >>> tweets[0]['text'] u'agora sim! Tudo bem, alvinegra? Mudou de foto, n\xe9? Gostei! Algu\xe9\xe9m ai?' >>> original = json.dumps(tweets) # convert it back to a string (and write to a file, say)

41 MongoDB Once created, JSON strings can be easily stored in one of several so-called NoSQL databases -- MongoDB is one example, and one that s running on our homework machine The next few slides have instructions about how to make use of Mongo, but please contact me before you do -- Right now Mongo is running without authentication (without any notion of users) and it s easy for someone to overwrite your work But if you want to take your homework assignments one step farther, you can use Mongo to store recipes and issue simple searches...

42

43 >>> import pymongo, re >>> rec1 = {"name":"venison and eggs",... "instructions":["mix well","bake","don't cut yourself"],... "ingredients":["3 eggs","some milk","venison!"]} >>> rec2 = {"name":"venison and pasta",... "instructions":["chop","sift","chop again"],... "ingredients":["linguini","some milk","venison!"]} >>> rec3 = {"name":"cheese and pasta",... "instructions":["stir","whisk"],... "ingredients":["linguini","american cheese"]} >>> conn = pymongo.connection() # connect to the db >>> type(conn) <class 'pymongo.connection.connection'> >>> db = conn.mh_test # reate a new database >>> recipes = db.fist_recipes # create a collection in the database >>> recipes.insert(rec1) >>> recipes.insert(rec2) >>> recipes.insert(rec3)

44 >>> # retrieving data from the db >>> recipes.find_one() {u'instructions': [u'mix well', u'bake', u"don't cut yourself"], u'_id': ObjectId('4cbf5ca51658f '), u'name': u'venison and eggs', u'ingredients': [u'3 eggs', u'some milk', u'venison!']} >>> ven = re.compile(".*venison.*") >>> for r in recipes.find({"name":ven}): print r... {u'instructions': [u'mix well', u'bake', u"don't cut yourself"], u'_id': ObjectId('4cbf5ca51658f '), u'name': u'venison and eggs', u'ingredients': [u'3 eggs', u'some milk', u'venison!']} {u'instructions': [u'chop', u'sift', u'chop again'], u'_id': ObjectId('4cbf5ca51658f '), u'name': u'venison and pasta', u'ingredients': [u'linguini', u'some milk', u'venison!']}

45 Your next homework For Wednesday, I want you to read a chapter in Saltzer and Kaashoek on Systems and Complexity -- I ll scan the chapter and put it up on our course Moodle page For our next assignment, we are going to build a system -- Specifically we are going to build something called Shazam, a music tagging system

46

47 Shazam The algorithm behind Shazam is fairly straightforward -- A time-frequency decomposition is performed examining which frequencies are dominant at which times in a song The peaks in this map forma kind of constellation -- Relationships between the individual elements are then encoded using something called geometric hashing (don t worry about this yet) Given a sample of audio, the same process is repeated and a search is made to see if there are matching patterns of peaks...

48

49

50

51 The goal The goal of this assignment is to have you design a system -- Each group will implement and end-to-end system that takes in an audio file, computes the needed decompositions and hashes and performs the match Your job is to divide the tasks and design a way to had data back and forth -- The emphasis is on cooperation, coordination, modularity For Wednesday, you are to read the book chapter, the original Shazam article and meet with your group to think about the basic system components -- You ll then write up a short proposal for how work should proceed

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : }

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : } Chapter 8 More Data Structures We have seen the list data structure and its uses. We will now examine two, more advanced data structures: the set and the dictionary. In particular, the dictionary is an

More information

Modules and scoping rules

Modules and scoping rules C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library

More information

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Basics of Python (Part 3): Functions, Lists, For Loops, and Tuples Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani

More information

Exception Handling and Debugging

Exception Handling and Debugging Exception Handling and Debugging Any good program makes use of a language s exception handling mechanisms. There is no better way to frustrate an end-user then by having them run into an issue with your

More information

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria CSE 399-004: Python Programming Lecture 5: Course project and Exceptions February 12, 2007 Announcements Still working on grading Homeworks 3 and 4 (and 2 ) Homework 5 will be out by tomorrow morning I

More information

Python File Modes. Mode Description. Open a file for reading. (default)

Python File Modes. Mode Description. Open a file for reading. (default) UNIT V FILES, MODULES, PACKAGES Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative

More information

Python Reference (The Right Way) Documentation

Python Reference (The Right Way) Documentation Python Reference (The Right Way) Documentation Release 0.1 Jakub Przywóski Sep 30, 2017 Contents 1 Contents 1 1.1 Introduction............................................... 1 1.2 Definitions................................................

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

Chapter 9: Dealing with Errors

Chapter 9: Dealing with Errors Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

SBT 645 Introduction to Scientific Computing in Sports Science #6

SBT 645 Introduction to Scientific Computing in Sports Science #6 SBT 645 Introduction to Scientific Computing in Sports Science #6 SERDAR ARITAN serdar.aritan@hacettepe.edu.tr Biyomekanik Araştırma Grubu www.biomech.hacettepe.edu.tr Spor Bilimleri Fakültesi www.sbt.hacettepe.edu.tr

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

CS Lecture 26: Grab Bag. Announcements

CS Lecture 26: Grab Bag. Announcements CS 1110 Lecture 26: Grab Bag Announcements The End is Nigh! 1. Next (last) lecture will be recap and final exam review 2. A5 due Wednesday night 3. Final exam 7pm Thursday May 15 in Barton Hall (East section)

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Exceptions CS GMU

Exceptions CS GMU Exceptions CS 112 @ GMU Exceptions When an unrecoverable action takes place, normal control flow is abandoned: an exception value crashes outwards until caught. various types of exception values can be

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

More information

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS (download slides and.py files and follow along!) 6.0001 LECTURE 7 6.0001 LECTURE 7 1 WE AIM FOR HIGH QUALITY AN ANALOGY WITH SOUP You are making soup but bugs

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

Lecture #12: Quick: Exceptions and SQL

Lecture #12: Quick: Exceptions and SQL UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

Overview. Recap of FP Classes Instances Inheritance Exceptions

Overview. Recap of FP Classes Instances Inheritance Exceptions Overview Recap of FP Classes Instances Inheritance Exceptions [len(s) for s in languages] ["python", "perl", "java", "c++"] map(len, languages) < 6, 4, 4, 3> [num for num in fibs if is_even(num)] [1, 1,

More information

Python for Informatics

Python for Informatics Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 3 Conditional execution 3.1 Boolean expressions A boolean expression is an expression that is either true or false.

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Python 3000 and You. Guido van Rossum PyCon March 14, 2008

Python 3000 and You. Guido van Rossum PyCon March 14, 2008 Python 3000 and You Guido van Rossum PyCon March 14, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Python. How You Can Do More Interesting Things With Python (Part II)

Python. How You Can Do More Interesting Things With Python (Part II) Python How You Can Do More Interesting Things With Python (Part II) Python for Statement for in : statement-block my_dict = { k1 : 1, k2 : 2 } for (k,v) in my_dict.items(): print(

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Introduction to Python programming, II

Introduction to Python programming, II GC3: Grid Computing Competence Center Introduction to Python programming, II (with a hint of MapReduce) Riccardo Murri Grid Computing Competence Center, University of Zurich Oct. 10, 2012 Today s class

More information

Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009

Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009 CSE 130 : Winter 2009 Programming Languages Lecture 11: What s in a Name? Today: Revisit some objects Exploit features and build powerful expressions Base: int, float, complex Sequence: string, tuple,

More information

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

ENVIRONMENT MODEL: FUNCTIONS, DATA 18 ENVIRONMENT MODEL: FUNCTIONS, DATA 18 COMPUTER SCIENCE 61A Jon Kotker and Tom Magrino July 18, 2012 1 Motivation Yesterday, we introduced the environment model of computation as an alternative to the earlier

More information

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating

More information

Lecture 18. Classes and Types

Lecture 18. Classes and Types Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Exceptions & error handling in Python 2 and Python 3

Exceptions & error handling in Python 2 and Python 3 Exceptions & error handling in Python 2 and Python 3 http://www.aleax.it/pycon16_eh.pdf 2016 Google -- aleax@google.com 1 Python in a Nutshell 3rd ed Chapter 5 of Early Release e-book version 50% off:

More information

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3] What is an Exception? Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem An exception is an abnormal condition (and thus rare)

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded

More information

Webgurukul Programming Language Course

Webgurukul Programming Language Course Webgurukul Programming Language Course Take One step towards IT profession with us Python Syllabus Python Training Overview > What are the Python Course Pre-requisites > Objectives of the Course > Who

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

1 Strings (Review) CS151: Problem Solving and Programming

1 Strings (Review) CS151: Problem Solving and Programming 1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote

More information

T H E I N T E R A C T I V E S H E L L

T H E I N T E R A C T I V E S H E L L 3 T H E I N T E R A C T I V E S H E L L The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. Ada Lovelace, October 1842 Before

More information

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 Course Web Site http://www.nps.navy.mil/cs/facultypages/squire/cs2900 All course related materials will be posted

More information

Python Tutorial. Day 1

Python Tutorial. Day 1 Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class MyClass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = MyClass('student', 'teacher')

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions

More information

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala Functions, Scope & Arguments HORT 59000 Lecture 12 Instructor: Kranthi Varala Functions Functions are logical groupings of statements to achieve a task. For example, a function to calculate the average

More information

This section provides some reminders and some terminology with which you might not be familiar.

This section provides some reminders and some terminology with which you might not be familiar. Chapter 3: Functions 3.1 Introduction The previous chapter assumed that all of your Bali code would be written inside a sole main function. But, as you have learned from previous programming courses, modularizing

More information

CGS 3066: Spring 2015 JavaScript Reference

CGS 3066: Spring 2015 JavaScript Reference CGS 3066: Spring 2015 JavaScript Reference Can also be used as a study guide. Only covers topics discussed in class. 1 Introduction JavaScript is a scripting language produced by Netscape for use within

More information

CNRS ANF PYTHON Objects everywhere

CNRS ANF PYTHON Objects everywhere CNRS ANF PYTHON Objects everywhere Marc Poinot Numerical Simulation Dept. Outline Python Object oriented features Basic OO concepts syntax More on Python classes multiple inheritance reuse introspection

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

Functions and Decomposition

Functions and Decomposition Unit 4 Functions and Decomposition Learning Outcomes Design and implement functions to carry out a particular task. Begin to evaluate when it is necessary to split some work into functions. Locate the

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

More information

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman 1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive

More information

Lecture 7: Representation

Lecture 7: Representation Lecture 7: Representation Last time We finished the Python introduction we started the previous lecture, talking briefly about BeautifulSoup and about a networking module that lets us fetch data from various

More information

Idioms and Anti-Idioms in Python

Idioms and Anti-Idioms in Python Idioms and Anti-Idioms in Python Release 2.6.3 Guido van Rossum Fred L. Drake, Jr., editor October 06, 2009 Python Software Foundation Email: docs@python.org Contents 1 Language Constructs You Should Not

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 9 Date:

More information

Python 3000 and You. Guido van Rossum EuroPython July 7, 2008

Python 3000 and You. Guido van Rossum EuroPython July 7, 2008 Python 3000 and You Guido van Rossum EuroPython July 7, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print

More information

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2 Python for Analytics Python Fundamentals RSI Chapters 1 and 2 Learning Objectives Theory: You should be able to explain... General programming terms like source code, interpreter, compiler, object code,

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Introduction to Python Part 2

Introduction to Python Part 2 Introduction to Python Part 2 v0.2 Brian Gregor Research Computing Services Information Services & Technology Tutorial Outline Part 2 Functions Tuples and dictionaries Modules numpy and matplotlib modules

More information

CS50 Supersection (for those less comfortable)

CS50 Supersection (for those less comfortable) CS50 Supersection (for those less comfortable) Friday, September 8, 2017 3 4pm, Science Center C Maria Zlatkova, Doug Lloyd Today s Topics Setting up CS50 IDE Variables and Data Types Conditions Boolean

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

(Refer Slide Time: 01:40)

(Refer Slide Time: 01:40) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #25 Javascript Part I Today will be talking about a language

More information

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections 6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How

More information

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

CPS122 Lecture: From Python to Java

CPS122 Lecture: From Python to Java Objectives: CPS122 Lecture: From Python to Java last revised January 7, 2013 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("

More information

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming File Operations Files are persistent data storage titanicdata.txt in PS06 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a program (exists

More information

a b c d a b c d e 5 e 7

a b c d a b c d e 5 e 7 COMPSCI 230 Homework 9 Due on April 5, 2016 Work on this assignment either alone or in pairs. You may work with different partners on different assignments, but you can only have up to one partner for

More information

4.3 FURTHER PROGRAMMING

4.3 FURTHER PROGRAMMING 4.3 FURTHER PROGRAMMING 4.3.3 EXCEPTION HANDLING EXCEPTION HANDLING An exception is a special condition that changes the normal flow of the program execution. That is, when an event occurs that the compiler

More information

Programming Languages

Programming Languages CSE 130 : Spring 2011 Programming Languages Lecture 13: What s in a Name? Ranjit Jhala UC San Diego Next: What s in a name? More precisely: How should programmer think of data What does a variable x really

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information