Introduction to Python programming, II

Size: px
Start display at page:

Download "Introduction to Python programming, II"

Transcription

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

2 Today s class More Python: objects and classes, list comprehensions, iteration and objects (again), exceptions, decorators, callable objects, etc. These slides are available for download from:

3 User-defined objects import unittest as ut class SpTest(ut.TestCase): def test_sp_1(self): (x, y) = sp(100, [5, 75, 25]) self.asserttrue((x,y) in [(75, 25), (25,75)]) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertequal((x,y), (4,4)) This was your first encounter with Python object, during the last Lab session. Today we are going to examine Python objects and classes in more detail.

4 Declare a new class, import unittest as ut ihneriting from ut.testcase. The body of class SpTest(ut.TestCase): the declaration is indented relative to the class def test_sp_1(self): statement. (x, y) = sp(100, [5, 75, 25]) self.asserttrue((x,y) in [(75,25), (25,75)]) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertequal((x,y), (4,4))

5 A method declaration looks import unittest as ut exactly like a function definition. Every method class SpTest(ut.TestCase): must have at least one argument, named self. def test_sp_1( self ): (x, y) = sp(100, [5, 75, 25]) self.asserttrue((x,y) in [(75,25), (25,75)]) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertequal((x,y), (4,4))

6 self is a reference to the import unittest as ut object instance (like, e.g., this in Java). It is used to class SpTest(ut.TestCase): access attributes and invoke methods of the def test_sp_1(self): instance itself. (x, y) = sp(100, [5, 75, 25]) self.asserttrue((x,y) in [(75, 25), (25,75)]) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertequal((x,y), (4,4))

7 The self argument Every method of a Python object always has self as first argument. However, you do not specify it when calling a method: it s automatically inserted by Python: >>> class ShowSelf(object):... def show(self):... print(self)... >>> x = ShowSelf() # construct instance >>> x.show() # self automatically inserted! < main.showself object at 0x299e150> The self variable is a reference to the object instance itself. You need to use self when accessing methods or attributes of this instance.

8 import unittest as ut These call methods defined on the current instance. class SpTest(ut.TestCase): Quiz: Where are they defined, exactly? def test_sp_1(self): (x, y) = sp(100, [5, 75, 25]) self.asserttrue ((x,y) in [(75, 25), (25,75)]) def test_sp_2(self): (x,y) = sp(8, [2,1,9,4,4,56,90,3]) self.assertequal ((x,y), (4,4))

9 Name resolution rules Within a function body, names are resolved according to the LEGB rule: L Local scope: any names defined in the current function; E Enclosing function scope: names defined in enclosing functions (outermost last); G global scope: names defined in the toplevel of the current module; B Built-in names (i.e., Python s module). builtins Any name that is not in one of the above scopes must be qualified. So you have to write self.assertequal to call a method on this instance, ut.testcase to mean a class defined in module ut, etc.

10 An easy exercise A dotfile is a file whose name starts with a dot character.. How can you list all dotfiles in a given directory? (Recall that the Python library call for listing the entries in a directory is os.listdir())

11 A very basic solution Use a for loop to accumulate the results into a list: dotfiles = [ ] for entry in os.listdir(path): if entry.startswith(. ): dotfiles.append(entry)

12 List comprehensions, I Python has a better and more compact syntax for filtering elements of a list and/or applying a function to them: dotfiles = [ entry for entry in dotfiles if entry.startswith(. ) ] This is called a list comprehension.

13 List comprehensions, II The general syntax of a list comprehension is: where: [ expr for var in iterable if condition ] expr is any Python expression; iterable is a (generalized) sequence; condition is a boolean expression, depending on var; var is a variable that will be bound in turn to each item in iterable which satisfies condition. The if condition part is optional.

14 Generator expressions List comprehensions are a special case of generator expressions: ( expr for var in iterable if condition ) A generator expression is a valid iterable and can be used to initialize tuples, sets, dicts, etc.: # the set of square numbers < 100 squares = set(n*n for n in range(10)) Generator expressions are valid expression, so they can be nested: # cartesian product of sets A and B C = set( (a,b) for a in A for b in B )

15 Generators Generator expressions are a special case of generators. A generator is like a function, except it uses yield instead of return: def squares(): n = 0 while True: yield n*n n += 1 At each iteration, execution resumes with the statement logically following yield in the generator s execution flow. There can be multiple yield statements in a generator. Reference:

16 The Iterator Protocol An object can function as an iterator iff it implements a next() method, that: either returns the next value in the iteration, or raises StopIteration to signal the end of the iteration. An object can be iterated over with for if it implements a iter () method. Reference:

17 Iterate over the words in class WordIterator(object): the given text: split the text at white spaces, and def init (self, text): return the parts self._words = text.split() one by one. def next(self): if len(self._words) > 0: return self._words.pop(0) else: raise StopIteration def iter (self): return self Source code available at:

18 class WordIterator( object ): def init (self, text): self._words = text.split() def next(self): if len(self._words) > 0: return self._words.pop(0) else: raise StopIteration def iter (self): return self Every class must inherit from a parent class. If there s no other class, inherit from the object class. (Root of the class hierarchy.)

19 class WordIterator(object): The constructor. def init (self, text): self._words = text.split() def next(self): if len(self._words) > 0: return self._words.pop(0) else: raise StopIteration def iter (self): return self

20 Constructors The init method is the object constructor. It should never return any value (other than None). However, you call a constructor by class name: # make w an instance of WordIterator w = WordIterator("some text") (Again, note that the self part is automatically inserted by Python.)

21 No overloading Python does not allow overloading of functions. Any function. Hence, no overloading of constructors. So: a class can have one and only one constructor.

22 Constructor chaining When a class is instanciated, Python only calls the first constructor it can find in the class inheritance call-chain. If you need to call a superclass constructor, you need to do it explicitly: class Application(Task): def init (self,...): # do Application-specific stuff here Task. init (self,...) # some more Application-specific stuff Calling a superclass constructor is optional, and it can happen anywhere in the init method body.

23 Multiple-inheritance Python allows multiple inheritance. Just list all the parent classes: class C(A,B): # class definition With multiple inheritance, it is your responsibility to call all the needed superclass constructors. Python uses the C3 algorithm to determine the call precedence in an inheritance chain. You can always query a class for its method resolution order, via the mro attribute: >>> C. mro (<class ex.c >, <class ex.a >, <class ex.b >, <type object >)

24 class WordIterator(object): This creates an attribute of the current object. def init (self, text): self. words = text.split() def next(self): if len(self._words) > 0: return self._words.pop(0) else: raise StopIteration def iter (self): return self

25 Object attributes A Python object is (in particular) a key-value mapping: attributes (keys) are valid identifiers, values can be any Python object. Any object has attributes, which you can access (create, read, overwrite) using the dot notation: # create or overwrite the name attribute of w w.name = "Joe" # get the value of w.name and print it print (w.name) So, in the constructor you create the required instance attributes using self.var =... Note: also methods are attributes!

26 No access control There are no public / private /etc. qualifiers for object attributes. Any code can create/read/overwrite/delete any attribute on any object. There are conventions, though: protected attributes: name private attributes: name (But again, note that this is not enforced by the system in any way.)

27 class WordIterator(object): def init (self, text): self._words = text.split() def next(self): if len(self._words) > 0: return self._words.pop(0) else: raise StopIteration def iter (self): return self Raise the StopIteration exception if there are no more words to return. (More on exceptions in a moment.)

28 class WordIterator(object): def init (self, text): self._words = text.split() def next(self): if len(self._words) > 0: return self._words.pop(0) else: raise StopIteration def iter (self): return self The iter method should return a valid iterator. Since this object is an iterator, just return self.

29 Using iterators Iterators can be used in a for loop: >>> for word in WordIterator("a nice sunny day"):... print * +word+ *,... *a* *nice* *sunny* *day* They can be composed with other iterators for effect: >>> for n, word in enumerate(worditerator("a...")):... print str(n)+ : +word,... 0:a 1:nice 2:sunny 3:day See also:

30 Exceptions Exceptions are objects that inherit from the built-in Exception class. To create a new exception just make a new class: class NewKindOfError(Exception): """ Do use the docstring to document what this error is about. """ pass Exceptions are handled by class name, so they usually do not need any new methods (although you are free to define some if needed). See also:

31 try: # code that might raise an exception except SomeException: # handle some exception except AnotherException, ex: # the actual Exception instance # is available as variable ex else: # performed on normal exit from try finally: # performed on exit in any case The optional else clause is executed if and when control flows off the end of the try clause. The optional finally clause is executed on exit from the try or except block in any case. Reference: stmts.html#try

32 Raising exceptions Use the raise statement with an Exception instance: if an_error_occurred: raise AnError("Spider sense is tingling.") Within an except clause, you can use raise with no arguments to re-raise the current exception: try: something() except ItDidntWork: do_cleanup() # re-raise exception to caller raise

33 Exception handling example Read lines from a CSV file, ignoring those that do not have the required number of fields. If other errors occur, abort. Close the file when done. job_state = { } # empty dict try: csv_file = open( jobs.csv, r ) for line in csv_file: line = line.strip() # remove trailing newline try: name, jobid, state = line.split(",") except ValueError: continue # ignore line job_state[jobid] = state except IOError: raise # up to caller finally: csv_file.close()

34 A common case The cleanup pattern is so common that Python has a special statement to deal with it: with open( jobs.csv, r ) as csv_file: for line in csv_file: line = line.strip() # remove trailing newline try: name, jobid, state = line.split(",") except ValueError: continue # ignore line job_state[jobid] = state The with statement ensures that the file is closed upon exit from the with block (for whatever reason). Reference: stmts.html#with

35 The context manager protocol Any object can be used in a with statement, provided it defines the following two methods: enter () Called upon entrance of the with block; it return value is assigned to the variable following as (if any). exit (exc_cls, exc_val, exc_tb) Called with three arguments upon exit from the block. If an exception occurred, the three arguments are the exception type, value and traceback; otherwise, the three argument are all set to None Quiz: Can you think of other examples where this could be useful? See also:

36 Functions are first-class in Python: so you can pass them as arguments to other functions, return them from a function, and hence modify them. The decorator def func(...): # function body is an alternate and more readable form for: def func(...): # function body func = decorator(func) Here, decorator is a function that takes a function as argument and returns (another) function.

37 Decorators Decorators are expressions that take a function and evaluate to a function. They are made possible (and interesting) because of two Python features: Functions are first-class. Functions can be defined inside other functions.

38 A debug decorator, I This is a real decorator, that modifies a function to print a log line with its calling parameters. def trace(func): name = func.func_name def substitute(*posargs, **kwargs): print ("Calling %s with args=%r, kwargs=%r" % (name, posargs, kwargs)) return func(*posargs, **kwargs) return substitute Source code available at:

39 A debug decorator, II So, for example this def factorial(n): return 1 if n==0 else n*factorial(n-1) Produces the following output: >>> factorial(3) Calling factorial with args=(2,), kwargs={} Calling factorial with args=(1,), kwargs={} Calling factorial with args=(0,), kwargs={} 6

40 Interlude: the ternary def factorial(n): return 1 if n==0 else n*factorial(n-1) Incidentally, this is the ternary operator, which in C and Java reads condition? if true : if false

41 The debug decorator explained def trace(func): name = func.func_name def substitute(*posargs, **kwargs): print ("Calling %s with args=%r, kwargs=%r" % (name, posargs, kwargs)) return func(*posargs, **kwargs) return substitute A decorator is just an ordinary function...

42 The debug decorator explained def trace(func): name = func.func_name def substitute(*posargs, **kwargs): print ("Calling %s with args=%r, kwargs=%r" % (name, posargs, kwargs)) return func(*posargs, **kwargs) return substitute... that creates an inner function...

43 The debug decorator explained def trace(func): name = func.func_name def substitute(*posargs, **kwargs): print ("Calling %s with args=%r, kwargs=%r" % (name, posargs, kwargs)) return func(*posargs, **kwargs) return substitute... which is then returned as result of the outer function.

44 The debug decorator explained def trace( func ): name = func.func name def substitute(*posargs, **kwargs): print ("Calling %s with args=%r, kwargs=%r" % ( name, posargs, kwargs)) return func (*posargs, **kwargs) return substitute Any names that are bound in the outer function are available in the inner function. Each invocation of the outer function creates a new set of bindings (i.e., two inner functions created by different invocations will not see each other s bindings).

45 star-arguments, I def trace(func): name = func.func_name def substitute( *posargs, **kwargs): print ("Calling %s with args=%r, kwargs=%r" % (name, posargs, kwargs)) return func(*posargs, **kwargs) return substitute In a function definition, * args indicates that the variable args is bound to the tuple of actual parameters that were passed to the function.

46 star-arguments, II def trace(func): name = func.func_name def substitute(*posargs, **kwargs): print ("Calling %s with args=%r, kwargs=%r" % (name, posargs, kwargs)) return func( *posargs, **kwargs) return substitute In a function call, * args indicates that the remaining positional arguments are taken from the sequence args.

47 star-star-arguments def trace(func): name = func.func_name def substitute(*posargs, **kwargs ): print ("Calling %s with args=%r, kwargs=%r" % (name, posargs, kwargs)) return func(*posargs, **kwargs ) return substitute Similarly, ** kwargs in a definition binds variable kwargs to a dictionary containing the passed keyword arguments. In a function call, ** kwargs takes additional keyword arguments from dictionary kwargs.

48 What s a decorator, again? Decorators are functions callable objects that take a function and return a function. An object is callable iff it defines a call () method. Functions are callable objects. class CallMe(object): def call (self, name="baby"): return ("Call me, %s" % name) >>> c = CallMe() >>> c() Call me, baby >>> c("mister") Call me, Mister A callable object may be called as if it were a function. The signature of the call () method determines the arguments used in the call.

49 Example: The memoize decorator The memoize decorator caches function results and re-uses them instead of running the computation again. class memoize(object): def init (self, func): self._func = func self._cache = dict() def call (self, *args): if args not in self._cache: self._cache[args] = self._func(*args) return self._cache[args] Source code available at:

50 Class attributes Classes are Python objects too, hence they can have attributes. Class attributes can be created with the variable assignment syntax in a class definition block: class A(object): class_attr = value def init (self): #... Class attributes are shared among all instances of the same class!

51 Class attributes example class AutoInc(object): _cnt = 0 def init (self): AutoInc._cnt += 1 self._value = AutoInc._cnt def value(self): return self._value Quiz: Create three instances of the class: u1, u2, u3. What would the value() method return for each of them?

52 Further reading Idiomatic Python: A presentation of Python programming idioms for writing better (simpler, cleaner and often faster) code, by David Goodger. The Zen of Python in 3 days: Great set of slides from a 3-day course, covering topics from the very basics of Python programming to advanced real-world topics like SQL ORM usage and web programming. A commented list of online resources on the course Wiki:

53 import antigravity (You need at least Python 2.7 for this to work, though.)

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

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

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

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

Mastering Python Decorators

Mastering Python Decorators Mastering Python Decorators One of the hallmarks of good Python is the judicious use of decorators to optimize, simplify and add new functionality to existing code. Decorators are usually seen as an advanced

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Classes Dr. David Koop Tuple, List, Dictionary, or Set? [1,2,"abc"] 2 Tuple, List, Dictionary, or Set? {"a", 1, 2} 3 Tuple, List, Dictionary, or Set? {} 4 Tuple,

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

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

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

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

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Eric Kutschera University of Pennsylvania January 30, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 January 30, 2015 1 / 31 Questions Homework

More information

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

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

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python Outline Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer Universität des Saarlandes October 6th, 2009 Outline Outline Today s Topics: 1 More Examples 2 Cool Stuff 3 Text Processing

More information

Python Decorators. Chris Calloway

Python Decorators. Chris Calloway Python Decorators Chris Calloway What is a Decorator? An object. What is a Decorator? An object. A callable object which is passed a function reference as its sole argument. What is a Decorator? An object.

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

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

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern CSE 399-004: Python Programming Lecture 12: Decorators April 9, 200 http://www.seas.upenn.edu/~cse39904/ Announcements Projects (code and documentation) are due: April 20, 200 at pm There will be informal

More information

Extending Jython. with SIM, SPARQL and SQL

Extending Jython. with SIM, SPARQL and SQL Extending Jython with SIM, SPARQL and SQL 1 Outline of topics Interesting features of Python and Jython Relational and semantic data models and query languages, triple stores, RDF Extending the Jython

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

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

F21SC Industrial Programming: Python: Classes and Exceptions

F21SC Industrial Programming: Python: Classes and Exceptions F21SC Industrial Programming: Python: Classes and Exceptions Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software

More information

Python Interview Questions & Answers

Python Interview Questions & Answers Python Interview Questions & Answers Q 1: What is Python? Ans: Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high

More information

CS 11 python track: lecture 2

CS 11 python track: lecture 2 CS 11 python track: lecture 2 Today: Odds and ends Introduction to object-oriented programming Exception handling Odds and ends List slice notation Multiline strings Docstrings List slices (1) a = [1,

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes Class definition F21SC Industrial Programming: Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2014/15 Class definition uses familiar

More information

Advanced Python. generators, decorators, context managers. Zbigniew Jędrzejewski-Szmek. George Mason University

Advanced Python. generators, decorators, context managers. Zbigniew Jędrzejewski-Szmek. George Mason University Advanced Python generators, decorators, context managers Zbigniew Jędrzejewski-Szmek George Mason University Python Summer School, Zürich, September 05, 2013 Version Zürich-98-ge13be00 This work is licensed

More information

Python Decorators. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 28, 2010

Python Decorators. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 28, 2010 Python Decorators Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 28, 2010 Stéphane Vialette (LIGM, Université Paris-Est Marne-la-Vallée) Python Decorators October 28, 2010 1 / 37

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

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2005 P. N. Hilfinger Project #2: Static Analyzer for Pyth Due: Wednesday, 6 April

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014 Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014 Intermission Rant about the history of this talk and why this topic matters. Python decorator syntax @function_wrapper def

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

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

IC Language Specification

IC Language Specification CS 301 Spring 2016 IC Language Specification The IC Language For the implementation project, you will build a compiler for an object-oriented language called IC (for Irish Coffee 1 ), which is essentially

More information

Recap: Functions as first-class values

Recap: Functions as first-class values Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

More information

Python Boot Camp. Day 3

Python Boot Camp. Day 3 Python Boot Camp Day 3 Agenda 1. Review Day 2 Exercises 2.Getting input from the user, Interview Lab 3.Scopes 4.Conditionals, Mood Ring Lab 5.Recursion, Recursion Lab Day 2 Exercises Think Python Ch. 3

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

Advanced topics, part 2

Advanced topics, part 2 CS 1 Introduction to Computer Programming Lecture 24: December 5, 2012 Advanced topics, part 2 Last time Advanced topics, lecture 1 recursion first-class functions lambda expressions higher-order functions

More information

Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors

Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors Objects (again) Professor Hugh C. Lauer CS-1004 Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction to Computer Science, 2 nd edition, by John

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Robert Rand University of Pennsylvania February 03, 2016 Robert Rand (University of Pennsylvania) CIS 192 February 03, 2016 1 / 23 Outline 1 Function Arguments

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

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Functions and Functional Programming Harry Smith University of Pennsylvania January 25, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 3 January 25, 2018 1 / 39

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

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang Chapter 1 Glossary For Introduction to Programming Using Python By Y. Daniel Liang.py Python script file extension name. assembler A software used to translate assemblylanguage programs into machine code.

More information

Software Development Python (Part B)

Software Development Python (Part B) Software Development Python (Part B) Davide Balzarotti Eurecom 1 List Comprehension It is a short way to construct a list based on the content of other existing lists Efficient Elegant Concise List comprehensions

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Structure and Flow. CS 3270 Chapter 5

Structure and Flow. CS 3270 Chapter 5 Structure and Flow CS 3270 Chapter 5 Python Programs Are made up of modules One module is the main (top-level) module The first one loaded (even if it s the interpreter) Its module object has main as its

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

LECTURE 2. Python Basics

LECTURE 2. Python Basics LECTURE 2 Python Basics MODULES ''' Module fib.py ''' from future import print_function def even_fib(n): total = 0 f1, f2 = 1, 2 while f1 < n: if f1 % 2 == 0: total = total + f1 f1, f2 = f2, f1 + f2 return

More information

Python debugging and beautification

Python debugging and beautification Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0

More information

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion CSC 148 Lecture 3 Dynamic Typing, Scoping, and Namespaces Recursion Announcements Python Ramp Up Session Monday June 1st, 1 5pm. BA3195 This will be a more detailed introduction to the Python language

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

PYTHON TRAINING COURSE CONTENT

PYTHON TRAINING COURSE CONTENT SECTION 1: INTRODUCTION What s python? Why do people use python? Some quotable quotes A python history lesson Advocacy news What s python good for? What s python not good for? The compulsory features list

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Object Model Comparisons

Object Model Comparisons Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until

More information

Advanced Python Subjects. By Imri Goldberg plnnr.com

Advanced Python Subjects. By Imri Goldberg   plnnr.com Advanced Python Subjects By Imri Goldberg www.algorithm.co.il plnnr.com Introduction Many people I know come to Python from C/C++. Including me! They bring with them many unpythonic idioms: inheritance

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

UCT Department of Computer Science Computer Science 1017F. Functions. Lighton Phiri April 2015

UCT Department of Computer Science Computer Science 1017F. Functions. Lighton Phiri April 2015 UCT Department of Computer Science Computer Science 1017F Functions Lighton Phiri April 2015 Functions in pespective Function definition Function signature Function invocation Input

More information

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona Defining Functions CSc 372 Comparative Programming Languages 5 : Haskell Function Definitions Department of Computer Science University of Arizona collberg@gmail.com When programming in a functional language

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Python Evaluation Rules

Python Evaluation Rules Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure

More information

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99 1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

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

Lecture no

Lecture no Advanced Algorithms and Computational Models (module A) Lecture no. 3 29-09-2014 Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 28 Expressions, Operators and Precedence Sequence Operators The following

More information

TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

More information

Comp 249 Programming Methodology Chapter 9 Exception Handling

Comp 249 Programming Methodology Chapter 9 Exception Handling Comp 249 Programming Methodology Chapter 9 Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

CircuitPython 101: Working with Lists, Iterators and Generators

CircuitPython 101: Working with Lists, Iterators and Generators CircuitPython 101: Working with Lists, Iterators and Generators Created by Dave Astels Last updated on 2018-11-01 12:06:56 PM UTC Guide Contents Guide Contents Overview List Functions Slicing Filtering

More information

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Notes on Higher Order Programming in Scheme. by Alexander Stepanov by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java expressions and operators concluded Java Statements: Conditionals: if/then, if/then/else Loops: while, for Next

More information

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

More information

The Decaf Language. 1 Lexical considerations

The Decaf Language. 1 Lexical considerations The Decaf Language In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance

More information

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

What we already know. more of what we know. results, searching for This 6/21/2017. chapter 14 What we already know chapter 14 Files and Exceptions II Files are bytes on disk. Two types, text and binary (we are working with text) open creates a connection between the disk contents and the program

More information

PYTHON CONTENT NOTE: Almost every task is explained with an example

PYTHON CONTENT NOTE: Almost every task is explained with an example PYTHON CONTENT NOTE: Almost every task is explained with an example Introduction: 1. What is a script and program? 2. Difference between scripting and programming languages? 3. What is Python? 4. Characteristics

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

Defining Functions III: Nested Definitions

Defining Functions III: Nested Definitions Defining Functions III: Nested Definitions The above examples demonstrate how the ability to pass functions as arguments significantly enhances the expressive power of our programming language. Each general

More information

CS 11 python track: lecture 4

CS 11 python track: lecture 4 CS 11 python track: lecture 4 Today: More odds and ends assertions "print >>" syntax more on argument lists functional programming tools list comprehensions More on exception handling More on object-oriented

More information

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs. Java SE11 Development Java is the most widely-used development language in the world today. It allows programmers to create objects that can interact with other objects to solve a problem. Explore Java

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

STATS Data Analysis using Python. Lecture 8: Hadoop and the mrjob package Some slides adapted from C. Budak

STATS Data Analysis using Python. Lecture 8: Hadoop and the mrjob package Some slides adapted from C. Budak STATS 700-002 Data Analysis using Python Lecture 8: Hadoop and the mrjob package Some slides adapted from C. Budak Recap Previous lecture: Hadoop/MapReduce framework in general Today s lecture: actually

More information

Functional Programming - 2. Higher Order Functions

Functional Programming - 2. Higher Order Functions Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

More information