Positional, keyword and default arguments

Size: px
Start display at page:

Download "Positional, keyword and default arguments"

Transcription

1 O More on Python n

2 O Functions n

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

4 Variable argument list in repl: >>> def func(fst, *args):... for arg in args: print(fst, arg)... >>> func("i love ", "apples", "Mozart", 42) ('I love ', 'apples') ('I love ', 'Mozart') ('I love ', 42)

5 Dictionaries as arguments in repl: >>> def func(fst, **args):... for key,value in args.items():... print(fst, key, " and ", value)... >>> func("i love ", apples="pears", life = 42) ('I love ', 'life', ' and ', 42) ('I love ', 'apples', ' and ', 'pears')

6 Unpacking arguments in repl: >>> def f(a,b):... print(a + " and " + b)... >>> f(*["a","b"]) a and b

7 Functions are objects in repl: >>> def func(arg):... print(arg)... >>> func <function func at 0x100492d70> >>> var = func >>> var("hello") Hello

8 Functions are objects... so we can pass them as arguments to other functions in repl: >>> def is_even(i):... return ((i % 2) == 0)... >>> m = map(is_even, range(6)) >>> m [True, False, True, False, True, False]

9 lambdas A lambda is an anonymous function Code executed as a nameless function Expressions only (no statements) If something more complex is needed, use defs def is a statement followed by a list of statements (it's possible to nest them) in repl: >>> s = map(lambda x: x * x, [2, 4]) >>> s [4, 16]

10 List Comprehensions The Proposed Solution It is proposed to allow conditional construction of list literals using for and if clauses. They would nest in the same way for loops and if statements nest now. Rationale List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used.

11 List Comprehensions Syntax: [x,y for...] is disallowed [(x,y) for...] instead [... for x... for y] y varies faster in repl: >>> xlist = [1,2,3] >>> ylist = [1,2,3] >>> [x + y for x in xlist for y in ylist] [2, 3, 4, 3, 4, 5, 4, 5, 6]

12 List Comprehensions >>> m = map(lambda n: n % 2 == 0, range(6)) >>> m [True, False, True, False, True, False] >>> [n % 2 == 0 for n in range(6)] [True, False, True, False, True, False] >>> f = filter(lambda n: n % 2 == 0, range(6)) >>> f [0, 2, 4] >>> [n for n in range(6) if x % 2 == 0] [0, 2, 4]

13 Set comprehensions >>> {x % 2 == 0 for x in range(6)} set([false, True]) >>> s = {"this", "is", "a", "set"} >>> s.add("this") >>> s set(['a', 'this', 'is', 'set'])

14 Magic methods Generally invoked by Python when using certain syntax >>> obj = object() >>> dir(obj) [' class ', ' delattr ', ' doc ', ' format ', ' getattribute ', ' hash ', ' init ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ']

15 Magic methods class n(object): def init (self, i): print "init" self.i = i def add (self, o): print "add" return self.i + o def int (self): print "int" return self.i def str (self): print "str" return str(self.i) >>> obj = n(10) init >>> obj + 10 add 20 >>> int(obj) int 10 >>> str(obj) str '10' >>> int(obj) int 10

16 Magic methods, again >>> def m(): >>> def n(): >>> pass >>> return n >>> f = m() >>> f <function main.n> >>> dir(f) [' call ', ' class ', ' closure ', ' code ', ' defaults ', ' delattr ', ' dict ', ' doc ', ' format ', ' get ', ' getattribute ', ' globals ', ' hash ', ' init ', ' module ', ' name ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

17 Example: call in repl: >>> square = lambda x: x * x >>> square(10) 100 >>> square. call (10) 100 >>> def square(x):... return x * x... >>> square(10) 100 >>> square. call (10) 100 >>> class Squarer(object):... def call (self, x):... return x * x... >>> square = Squarer() >>> square(10) 100 >>> square. call (10) 100

18 O Exceptions n

19 in repl: >>> def print_list(lst, index):... element = lst[index]... print(element)... >>> lst = range(5) >>> print_list(lst, 1) 1 >>> print_list(lst, 9) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in print_list IndexError: list index out of range

20 in repl: >>> def print_list(lst, index):... try:... element = lst[index]... except IndexError as e:... print(e)... else:... print(element)... >>> lst = range(5) >>> print_list(lst, 1) 1 >>> print_list(lst, 9) list index out of range

21 in repl: >>> try:... f = open("non-existing-file", "r")... except IOError:... print("must... pass... on...")... raise... finally:... print("finally!")... if file is not None:... file.close()... Must... pass... on... Finally! Traceback (most recent call last): File "<stdin>", line 2, in <module> IOError: [Errno 2] No such file or directory: 'non-existing-file'

22 O Namespaces n

23 Namespaces A namespace is a set of mappings between a name and an object In Python this is currently implemented as dictionaries where the key is the variable name and the value is the value the variable refers to Therefore, a namespace can be accessed as a dictionary

24 Namespaces When we ask for the value of a variable, Python will search for it in 1. local namespace(s) -- innermost nesting level first 2. global namespace 3. built-in namespace If the name can not be found, Python will raise a NameError

25 Namespaces builtins : holds built-in functions, types and exceptions global NS for each module: holds classes, functions, variables and other imported modules local NS for each function: holds function arguments and any locally defined variables

26 Namespaces Assignment to a variable introduces the name to the local namespace To make the variable global, the global keyword can be used

27 Making the local global in repl: >>> x = 10 >>> def l_change_x():... x=2... >>> l_change_x() >>> print x 10 in repl: >>> x = 10 >>> def g_change_x():... global x... x = >>> g_change_x() >>> print x 20

28 O Classes Again n

29 Visibility Python assumes programmers are grown up, responsible people Everything is public If you wish to indicate that an attribute is used for implementation purposes and should NOT be messed with: name the attribute with a leading underscore -- _x

30 Classes - background Prior to Python 2.2, user defined types were inherently different from built-in types (e.g. list, int...) You could not inherit from built-in types Python 2.2 was the first step towards typeclass unification

31 Classes - background User defined types pre 2.2 are generally referred to as old-style classes In Python 2.2 new-style classes were introduced Old-style classes and new-style classes coexist in Python , but they are removed in Python 3.0+

32 Classes - background A classic class is a class that is defined with a class statement that has no new style classes amongst its base classes, i.e. inherits from no other class, or only from classic classes, applying the definition recursively A new-style class has the built-in object class as one of its base classes

33 Classes in Python 2.2+ (These definitions are equivalent in Python 3.0+) Old-style classes class SomeClass: <statement-1>.. <statement-n> in repl: >>> class A:... pass... >>> dir(a) [' doc ', ' module '] New-style classes class SomeClass(object): <statement-1>.. <statement-n> >>> class A(object):... pass... >>> dir(a) [' class ', ' delattr ', ' dict ', ' doc ', ' format ', ' getattribute ', ' hash ', ' init ', ' module ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ', ' weakref ']

34 Defining classes When entering a class definition, Python will introduce a new namespace for that class Attributes and function definitions will bind to this new namespace in repl: >>> class A(object):... a = >>> A.a 10

35 Defining classes in repl: >>> class A(object):... def init (self, name):... self.name = name... def hi(self):... print self.name, " says hi!"... >>> A <class ' main.a'> When a class definition is left (at the end of the block) a new class object will be created This new object will be bound to the current scope (name space)

36 in repl: Defining classes >>> A <class ' main.a'> >>> A. init <unbound method A. init > >>> a = A("test") >>> a. init <bound method A. init of < main.a object at 0x1005a6150>> >>> a.hi() test says hi! >>> A.hi(a) # equivalent with previous line test says hi! The first argument in function definitions will be reserved for the instance object which the method will operate on This argument is typically named self, but it is legal to name it this or whatever

37 Class objects Basically, you can only do two things with a class object: Reference attributes -- SomeClass.x Create instances -- a = A( Python )

38 But...

39 As we saw before: Method objects A. dict [' str '] <function str at 0x10049d0c8> >>> a = A(4) >>> a. str <bound method A. str of < main.a object at 0x >>

40 O The End n

41 References Programming Python by Mark Lutz Descriptor.htm

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

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

More information

Fundamentals of Programming. Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014

Fundamentals of Programming. Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014 15-112 Fundamentals of Programming Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014 Today Briefly show file and web IO. Revisit functions. Learn a bit more about them. Event-based

More information

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012 CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012 COMPUTER SCIENCE IN THE NEWS http://www.iospress.nl/ios_news/music to my eyes device converting

More information

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes chapter 11 Code Listing 11.1 First Class Introduction to Classes What is a class? If you have done anything in computer science before, you likely will have heard the term object oriented programming (OOP)

More information

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010 The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 11 Introduction to Classes class Student(object): """Simple Student class.""" def init (self,first='', last='', id=0): # init

More information

Functions #5. Serdar ARITAN. Department of Computer Graphics Hacettepe University, Ankara, Turkey

Functions #5. Serdar ARITAN. Department of Computer Graphics Hacettepe University, Ankara, Turkey #5 Serdar ARITAN Department of Computer Graphics Hacettepe University, Ankara, Turkey 1 I have never considered Python to be heavily influenced by functional languages, no matter what people say or think.

More information

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

Python OOP. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 19, 2010 Python OOP Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 19, 2010 Stéphane Vialette (LIGM, Université Paris-Est Marne-la-Vallée) Python OOP October 19, 2010 1 / 59 Outline 1 Introduction

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

Assignment 7: functions and closure conversion (part 1)

Assignment 7: functions and closure conversion (part 1) Assignment 7: functions and closure conversion (part 1) ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek November 12, 2008 The main ideas for this week are: first-class functions lexical scoping

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

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018 6. Object-Oriented Programming, II Programming and Algorithms II Degree in Bioinformatics Fall 2018 Inheritance class Carnivora(Animal): class Canid(Carnivora): class Dog(Canid): class Husky(Dog): class

More information

Isak Karlson Whatispython?

Isak Karlson Whatispython? MoreonPython Isak Karlson isak-kar@dsv.su.se Whatispython? Tableofcontents Whousespython? Modules Functions Namespaces Clases Descriptors PythonProperties PythonProperties,cont'd Dynamic,multi-paradigm

More information

Introduction to Python programming, II

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

More information

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.) CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

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

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

Object-Oriented Python

Object-Oriented Python Object-Oriented Python Everything is an object. Every object has a value. a type. an identity. a namespace. CS105 Python def initstudent(student, eid): global A class is like a namespace. CS105 Python

More information

Beyond Blocks: Python Session #1

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

More information

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Program Structure # Print "hello world" to stdout. print 'hello, world' # Print "hello world" to stdout. def f(): print

More information

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.) CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

More information

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

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

More information

Assignment 7: functions and closure conversion

Assignment 7: functions and closure conversion Assignment 7: functions and closure conversion ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek October 20, 2007 The main ideas for this week are: first-class functions lexical scoping of variables

More information

Introduction to Python programming, II

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

More information

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

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

More information

Sage Reference Manual: Python technicalities

Sage Reference Manual: Python technicalities Sage Reference Manual: Python technicalities Release 8.1 The Sage Development Team Dec 09, 2017 CONTENTS 1 Various functions to debug Python internals 3 2 Variants of getattr() 5 3 Metaclasses for Cython

More information

Python Tutorial. Day 1

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

More information

MEIN 50010: Python Flow Control

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

More information

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

Fun with Python Descriptors

Fun with Python Descriptors Fun with Python Descriptors Author: Jeff Rush Date: 2006-11-25 include directive disabled... include:: Overview What are descriptors? Implementation: attribute watcher Implementation: property()

More information

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

(IUCAA, Pune)   kaustubh[at]iucaa[dot]ernet[dot]in. Basics of Python - 2 by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 54 Sunday 16 February 2014 05:30 PM Our First Program - Rewritten! Let us introduce the following

More information

61A Lecture 2. Friday, August 28, 2015

61A Lecture 2. Friday, August 28, 2015 61A Lecture 2 Friday, August 28, 2015 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions: max

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

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 An Introduction

Python An Introduction Python An Introduction Calle Lejdfors and Lennart Ohlsson calle.lejdfors@cs.lth.se Python An Introduction p. 1 Overview Basic Python Numpy Python An Introduction p. 2 What is Python? Python plays a key

More information

All-Singing All-Dancing Python Bytecode Larry Hastings EuroPython 2013 July 2, 2013

All-Singing All-Dancing Python Bytecode Larry Hastings EuroPython 2013 July 2, 2013 All-Singing All-Dancing Python Bytecode Larry Hastings larry@hastings.org EuroPython 2013 July 2, 2013 Introduction Intermediate CPython 3.3.0 100% roughly applicable elsewhere What Is Bytecode? Opcodes

More information

Dangerously Advanced Python

Dangerously Advanced Python Dangerously Advanced Python Mike Verdone for Protospace, Calgary May 2009 http://mike.verdone.ca/ Introspection and Metaprogramming Introspection: Programs that can interrogate their own data structures

More information

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

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

\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

What's New in Python 2.2

What's New in Python 2.2 What's New in Python 2.2 LinuxWorld - New York City - January 2002 Guido van Rossum Director of PythonLabs at Zope Corporation guido@python.org guido@zope.com Overview Appetizers Nested Scopes Int/Long

More information

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

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

More information

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

Iterators & Generators

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

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

Python Programming: Lecture 3 Functions

Python Programming: Lecture 3 Functions Python Programming: Lecture 3 Functions Lili Dworkin University of Pennsylvania Last Week s Quiz In one line, write code that will turn the list [9, 9, 9] into the string 90909. Last Week s Quiz In one

More information

Introduction to Programming in Python (2)

Introduction to Programming in Python (2) Introduction to Programming in Python (2) Steve Renals s.renals@ed.ac.uk ICL 29 September 2005 Conditionals Loops Function basics Variables and functions Functional programming Designing functions Python

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

Objects CHAPTER 6. FIGURE 1. Concrete syntax for the P 3 subset of Python. (In addition to that of P 2.)

Objects CHAPTER 6. FIGURE 1. Concrete syntax for the P 3 subset of Python. (In addition to that of P 2.) CHAPTER 6 Objects The main ideas for this chapter are: objects and classes: objects are values that bundle together some data (attributes) and some functions (methods). Classes are values that describe

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers Python Tutorial Lecture for EE562 Artificial Intelligence for Engineers 1 Why Python for AI? For many years, we used Lisp, because it handled lists and trees really well, had garbage collection, and didn

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

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

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I ECE 364 Software Engineering Tools Lab Lecture 8 Python: Advanced I 1 Python Variables Namespaces and Scope Modules Exceptions Lecture Summary 2 More on Python Variables All variables in Python are actually

More information

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12 List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py

More information

Advanced Python. Executive Summary, Session 1

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

More information

RLISTS AND THE ENVIRONMENT MODEL 9

RLISTS AND THE ENVIRONMENT MODEL 9 RLISTS AND THE ENVIRONMENT MODEL 9 COMPUTER SCIENCE 61A July 17, 2012 1 Recursive Lists (RLists) Earlier in the course, we worked with the Immutable Recursive List (IRList), which is an abstract data type

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

Effective Programming Practices for Economists

Effective Programming Practices for Economists Effective Programming Practices for Economists 14. Object-oriented programming Hans-Martin von Gaudecker Department of Economics, Universität Bonn Revisiting abstractions Reminder of the example Reconsider

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

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

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

More information

Modules and scoping rules

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

More information

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

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

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 10: Functional programming, Memoization March 26, 2007 http://www.seas.upenn.edu/~cse39904/ Announcements Should have received email about meeting times Length:

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

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

CS Programming Languages: Scala

CS Programming Languages: Scala CS 3101-2 - Programming Languages: Scala Lecture 3: Fun with Functions Daniel Bauer (bauer@cs.columbia.edu) October 29, 2014 Daniel Bauer CS3101-2 Scala - 03 - Fun with Functions 1/37 Contents 1 Defining

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

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

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

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

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

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

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

More information

Python 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

FILE HANDLING AND EXCEPTIONS

FILE HANDLING AND EXCEPTIONS FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob

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

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

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

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers Lecture 27 Lecture 27: Regular Expressions and Python Identifiers Python Syntax Python syntax makes very few restrictions on the ways that we can name our variables, functions, and classes. Variables names

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

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

(CC)A-NC 2.5 by Randall Munroe Python

(CC)A-NC 2.5 by Randall Munroe Python http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional

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

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

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

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

More information

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

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

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 61A Extra Lecture 6 Announcements Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 Homework 3 is to complete an extension to Project 4 Due at the same time as Project

More information

Introduction to programming using Python

Introduction to programming using Python Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 4 1 Objectives To come back on the notion of object and type. To introduce to the

More information

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University Introductory Linux Course Martin Dahlö UPPMAX Author: Nina Fischer Dept. for Cell and Molecular Biology, Uppsala University August, 2018 Outline Python basics get started with Python Data types Control

More information

Lecture 16: Static Semantics Overview 1

Lecture 16: Static Semantics Overview 1 Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis

More information

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics

CS2304: Python for Java Programmers. CS2304: Advanced Function Topics CS2304: Advanced Function Topics Functions With An Arbitrary Number of Parameters Let s say you wanted to create a function where you don t know the exact number of parameters. Python gives you a few ways

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 8 March 28, 2016 Computational Concepts Toolbox Data type: values, literals,

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

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

Within each grouping, imports should be sorted lexicographically, ignoring case, according to each module's full package path.

Within each grouping, imports should be sorted lexicographically, ignoring case, according to each module's full package path. Python Style Guide This document is based on the Google Python Style Guide. The original document is comprehensive and should be referred for work outside the MADlib team. This document is specific to

More information

Harness the power of Python magic methods and lazy objects.

Harness the power of Python magic methods and lazy objects. Harness the power of Python magic methods and lazy objects. By Sep Dehpour Aug 2016 zepworks.com sep at zepworks.com https://github.com/seperman/redisworks Lazy Loading Defer initialization of an object

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

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