Introduction to Python programming, II

Size: px
Start display at page:

Download "Introduction to Python programming, II"

Transcription

1 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

2 Today s class Explain more Python constructs and semantics by looking at John Arley Burns MapReduce in 98 lines of Python. These slides are available for download from:

3 References See the course website for an extensive and commented list. Dean, J., and Ghemawat, S.: MapReduce: Simplified Data Processing on Large Clusters, OSDI 04 Greiner, J., Wong, S.: Distributed Parallel Processing with MapReduce Carter, J.: Simple MapReduce with Ruby and Rinda

4 What is MapReduce? MapReduce is: 1. a programming model 2. an associated implementation Both are important!!

5 MapReduce The Map function processes a key/value pair to produce intermediate key/value pairs. Image source: Greiner, J., Wong, S.: Distributed Parallel Processing with MapReduce

6 MapReduce The Reduce function merges all intermediate values associated with a given key. Image source: Greiner, J., Wong, S.: Distributed Parallel Processing with MapReduce

7 MapReduce: advantages of the model Programs written in this style are automatically parallelized and executed on a large cluster of machines... Quoted from: Dean and Ghemawat: MapReduce: Simplified Data Processing on Large Clusters

8 Example: word count Input is a text file, to be split at line boundaries. Image source:

9 Example: word count The Map function scans an input line and outputs a pair (word, 1) for each word in the text line. Image source:

10 Example: word count The pairs are shuffled and sorted so that each reducer gets all pairs (word, 1) with the same word part. Image source:

11 Example: word count The Reduce function gets all pairs (word, 1) with the same word part, and outputs a single pair (word, count) where count is the number of input items received. Image source:

12 Example: word count The global output is a list of pairs (word, count) where count is the number of occurences of word in the input text. Image source:

13 MapReduce: features of the implementation The run-time system takes care of the details: partitioning the input data, scheduling the program execution, handling machine failures, managing the required inter-machine communication. Quoted from: Dean and Ghemawat: MapReduce: Simplified Data Processing on Large Clusters

14 MapReduce: features of the implementation The run-time system takes care of the details: partitioning the input data, scheduling the program execution, handling machine failures, managing the required inter-machine communication. Quoted from: Dean and Ghemawat: MapReduce: Simplified Data Processing on Large Clusters

15 MapReduce: features of the implementation The run-time system takes care of the details: partitioning the input data, scheduling the program execution, handling machine failures, managing the required inter-machine communication. Quoted from: Dean and Ghemawat: MapReduce: Simplified Data Processing on Large Clusters

16 MapReduce: features of the implementation The run-time system takes care of the details: partitioning the input data, scheduling the program execution, handling machine failures, managing the required inter-machine communication. Quoted from: Dean and Ghemawat: MapReduce: Simplified Data Processing on Large Clusters

17 MapReduce: features of the implementation The run-time system takes care of the details: partitioning the input data, scheduling the program execution, handling machine failures, managing the required inter-machine communication. Quoted from: Dean and Ghemawat: MapReduce: Simplified Data Processing on Large Clusters

18 MapReduce: features of the implementation The run-time system takes care of the details: partitioning the input data, scheduling the program execution, handling machine failures, managing the required inter-machine communication. These are all highly nontrivial tasks to handle! The quality of a MapReduce implementation should be judged by how effective it is at handling the non-map/reduce part.

19 Back to Python! mapreduce.py by John Arley Burns is a simple Python class that simulates running a MapReduce algorithm using in-memory data structures. A MapReduce algorithm is specified by subclassing the MapReduce class and overriding methods to provide the Split, Map, and Reduce functions. (There s no Partition/Shuffle function because all the data is kept in memory and sorted there, so no locality issues.)

20 import re from mapreduce import MapReduce class WordCount(MapReduce): def init (self, data): MapReduce. init (self) self.data = data The word count example using mapreduce.py def split_fn(self, data): def line_to_tuple(line): return (None, line) data_list = [ line_to_tuple(line) for line in data.splitlines() ] return data_list def map_fn(self, key, value): for word in re.split(r \W+, value.lower()): bareword = re.sub(r"[ˆa-za-z0-9]*", r"", word); if len(bareword) > 0: yield (bareword, 1) def reduce_fn(self, word, count_list): return [(word, sum(count_list))] def output_fn(self, output_list): sorted_list = sorted(output_list, key=operator.itemgetter(1)) for word, count in sorted_list: print(word, count)

21 Importing modules This imports the re import re (regular expressions) from mapreduce import MapReduce module. class WordCount(MapReduce): #... def map_fn(self, key, value): for word in re.split (...): #... bareword = re.sub (...) if len(bareword) > 0: yield (bareword, 1) All names defined in that module are now visible under the re namespace, e.g., re.sub, re.split.

22 Importing names import re from mapreduce import MapReduce class WordCount( MapReduce ): def init (self, data): MapReduce. init (self) self.data = data #... This imports the MapReduce name, defined in the mapreduce module, into this module s namespace. So you need not use a prefix to qualify it.

23 Defining objects class WordCount(MapReduce): def init (self, data): MapReduce. init (self) self.data = data #... The class keyword starts the definition of a class (in the OOP sense). The class definition is indented.

24 Inheritance class WordCount( MapReduce ): def init (self, data): MapReduce. init (self) self.data = data #... This tells Python that the WordCount class inherits from the MapReduce class. Every class must inherit from some other class; the root of the class hierarchy is the built-in object class.

25 Declaring methods class WordCount(MapReduce): def init (self, data): MapReduce. init (self) self.data = data #... A method declaration looks exactly like a function definition. Every method must have at least one argument, named self. (Why the double underscore? More on this later!)

26 The self argument class WordCount(MapReduce): def init ( self, data): MapReduce. init ( self ) self.data = data #... self is a reference to the object instance (like, e.g., this in Java). It is used to access attributes and invoke methods of the instance itself.

27 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.

28 The self argument class WordCount(MapReduce): def init (self, data): MapReduce. init (self) self.data = data #... Q: (1) Why is the data identifier qualified with the self. namespace?

29 The self argument class WordCount(MapReduce): def init (self, data): MapReduce. init ( self ) self.data = data Q: (2) Why do we explicitly write self here? #...

30 Name resolution rules Within a function/method 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.data to call a method on this instance, re.sub to mean a function defined in module re, MapReduce. init to reference a method defined in the MapReduce class, etc.

31 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!

32 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.)

33 Class attributes, I 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!

34 Class attributes, II Methods are class attributes, too. However, looking up a method attribute on an instance returns a bound method, i.e., one for which self is automatically inserted. Looking up the same method on a class, returns an unbound method, which is just like a regular function, i.e., you must pass self explicitly.

35 Constructors, I class WordCount(MapReduce): def init (self, data): MapReduce. init (self) self.data = data #... The init method is the instance constructor. It should never return any value (other than None).

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

37 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.

38 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 WordCount(MapReduce): def init (self,...): # do WordCount-specific stuff here MapReduce. init (self,...) # some more WordCount-specific stuff Calling a superclass constructor is optional, and it can happen anywhere in the init method body.

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

40 Nested functions import re class WordCount(MapReduce): #... def split_fn(self, data): def line to tuple(line): return (None, line) data_list = [ line to tuple (line) for line in data.splitlines() ] return data_list #... You can define functions (and classes) within functions. The nested functions are only visible within the enclosing function. (But they can capture any variable from the enclosing function environment by name.)

41 List comprehensions, I Q: What is this? class WordCount(MapReduce): #... def split_fn(self, data): def line_to_tuple(line): return (None, line) data list = [ line to tuple(line) for line in data.splitlines() ] return data_list #...

42 An easy exercise A dotfile is a file whose name starts with a dot character.. How can you list the full pathname of all dotfiles in a given directory? (The Python library call for listing the entries in a directory is os.listdir(), which returns a list of file names.)

43 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( os.path.join(path, entry))

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

45 List comprehensions, III 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.

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

47 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:

48 Generators in action class WordCount(MapReduce): #... This makes map fn into a generator that return pairs (word, 1) def map_fn(self, key, value): for word in re.split(r \W+, value.lower()): bareword = re.sub(r"[ˆa-za-z0-9]*", r"", word); if len(bareword) > 0: yield (bareword, 1) #...

49 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:

50 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:

51 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.)

52 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:

53 class WordIterator(object): Q: What is this? 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

54 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:

55 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

56 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

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

58 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

59 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 Q: Can you think of other examples where this could be useful? See also:

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

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

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

\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

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

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

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

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

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

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

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

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

Programming I. Course 9 Introduction to programming

Programming I. Course 9 Introduction to programming Programming I Course 9 Introduction to programming What we talked about? Modules List Comprehension Generators Recursive Functions Files What we talk today? Object Oriented Programming Classes Objects

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

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

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

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

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

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

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

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

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

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

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

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

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

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

Basic Object-Oriented Concepts. 5-Oct-17

Basic Object-Oriented Concepts. 5-Oct-17 Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains

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

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

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

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

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

List Comprehensions. Function Definitions. This is the same as mapping the doubling function on the list [1,2,3], but without an explicit

List Comprehensions. Function Definitions. This is the same as mapping the doubling function on the list [1,2,3], but without an explicit List Comprehensions Python provides an elegant mechanism for building a list by embedding a for within list brackets. This a termed a List Comprehension. The general form is an expression, followed by

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

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

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

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

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

S206E Lecture 19, 5/24/2016, Python an overview

S206E Lecture 19, 5/24/2016, Python an overview S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their

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

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

Lessons on Python Classes and Objects

Lessons on Python Classes and Objects Lessons on Python Classes and Objects Walter Didimo [ 120 minutes ] Outline We will introduce basic concepts about classes and objects in Python a comprehensive lesson on this topic would require much

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

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing

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

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

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

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

Introduction to MapReduce

Introduction to MapReduce 732A54 Big Data Analytics Introduction to MapReduce Christoph Kessler IDA, Linköping University Towards Parallel Processing of Big-Data Big Data too large to be read+processed in reasonable time by 1 server

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

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

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

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

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

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

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 4 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE 341, Autumn 2015, Ruby Introduction Summary CSE 341, Autumn 2015, Ruby Introduction Summary Disclaimer: This lecture summary is not necessarily a complete substitute for atting class, reading the associated code, etc. It is designed to be a useful

More information

GNU ccscript Scripting Guide IV

GNU ccscript Scripting Guide IV GNU ccscript Scripting Guide IV David Sugar GNU Telephony 2008-08-20 (The text was slightly edited in 2017.) Contents 1 Introduction 1 2 Script file layout 2 3 Statements and syntax 4 4 Loops and conditionals

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

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

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

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

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

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

NAME CHSM-Java Concurrent, Hierarchical, Finite State Machine specification language for Java

NAME CHSM-Java Concurrent, Hierarchical, Finite State Machine specification language for Java NAME CHSM-Java Concurrent, Hierarchical, Finite State Machine specification language for Java SYNOPSIS declarations description user-code DESCRIPTION The CHSM specification language is a text-based means

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

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

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

PTN-102 Python programming

PTN-102 Python programming PTN-102 Python programming COURSE DESCRIPTION Prerequisite: basic Linux/UNIX and programming skills. Delivery Method Instructor-led training (ILT) Duration Four days Course outline Chapter 1: Introduction

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

Definition of DJ (Diminished Java)

Definition of DJ (Diminished Java) Definition of DJ (Diminished Java) version 0.5 Jay Ligatti 1 Introduction DJ is a small programming language similar to Java. DJ has been designed to try to satisfy two opposing goals: 1. DJ is a complete

More information

Course Title: Python + Django for Web Application

Course Title: Python + Django for Web Application Course Title: Python + Django for Web Application Duration: 6 days Introduction This course offer Python + Django framework ( MTV ) training with hands on session using Eclipse+Pydev Environment. Python

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

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Chapter 12 Outline Overview of Object Database Concepts Object-Relational Features Object Database Extensions to SQL ODMG Object Model and the Object Definition Language ODL Object Database Conceptual

More information

PREPARING FOR PRELIM 2

PREPARING FOR PRELIM 2 PREPARING FOR PRELIM 2 CS 1110: FALL 2012 This handout explains what you have to know for the second prelim. There will be a review session with detailed examples to help you study. To prepare for the

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction 2. Objects and classes 3. Information hiding 4. Constructors 5. Some examples of Java classes 6. Inheritance revisited 7. The class hierarchy

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

Exception Handling. Genome 559

Exception Handling. Genome 559 Exception Handling Genome 559 Review - classes Use your own classes to: - package together related data - conceptually organize your code - force a user to conform to your expectations Class constructor:

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

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

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 PS07 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a running program

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

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators Sven Schmit stanford.edu/~schmit/cme193 6: Classes and iterators 6-1 Contents Classes Generators and Iterators Exercises 6: Classes

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

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

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

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010 IPCoreL Programming Language Reference Manual Phillip Duane Douglas, Jr. 11/3/2010 The IPCoreL Programming Language Reference Manual provides concise information about the grammar, syntax, semantics, and

More information

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace ? User Defined Types Babes-Bolyai University arthur@cs.ubbcluj.ro Overview? 1? 2 3 ? NB! Types classify values. A type denotes a domain (a set of values) operations on those values. ? Object oriented programming

More information

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1 A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

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

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

Python-2. None. Special constant that is a null value

Python-2. None. Special constant that is a null value Python-2 None value in Python Iterators and generators Using them with file input Exceptions Modules (e.g., Python libraries) Using file I/O Walking a directory structure w. os module Using regular expressions

More information

// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function

// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function SFU CMPT 379 Compilers Spring 2015 Assignment 4 Assignment due Thursday, April 9, by 11:59pm. For this assignment, you are to expand your Bunting-3 compiler from assignment 3 to handle Bunting-4. Project

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

A Crash Course in Python Part II. Presented by Cuauhtémoc Carbajal ITESM CEM

A Crash Course in Python Part II. Presented by Cuauhtémoc Carbajal ITESM CEM A Crash Course in Python Part II Presented by Cuauhtémoc Carbajal ITESM CEM 1 Importing and Modules 2 Importing and Modules Use classes & functions defined in another file A Python module is a file with

More information

GBIL: Generic Binary Instrumentation Language. Language Reference Manual. By: Andrew Calvano. COMS W4115 Fall 2015 CVN

GBIL: Generic Binary Instrumentation Language. Language Reference Manual. By: Andrew Calvano. COMS W4115 Fall 2015 CVN GBIL: Generic Binary Instrumentation Language Language Reference Manual By: Andrew Calvano COMS W4115 Fall 2015 CVN Table of Contents 1) Introduction 2) Lexical Conventions 1. Tokens 2. Whitespace 3. Comments

More information