7-Sep-15 Python structure  modules: Python source files or C extensions  import, top-level via from, reload  statements  control flow  create objects.

Slides:



Advertisements
Similar presentations
Web编程技术 Web Programming Technology
Advertisements

Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Container Types in Python
Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
An Introduction to Python and Its Use in Bioinformatics
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Python: a modern hybrid A language for scripting and prototyping Balance between extensibility and powerful built-in data structures genealogy: –Setl (NYU,
25-Jun-15Advanced Programming Spring 2002 Python Henning Schulzrinne Department of Computer Science Columbia University (based on tutorial by Guido van.
1 Outline 7.1 Introduction 7.2 Implementing a Time Abstract Data Type with a Class 7.3 Special Attributes 7.4Controlling Access to Attributes 7.4.1Get.
Introduction to Python. What is Python? Interpreted object oriented high level programming language – No compiling or linking neccesary Extensible: add.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
CIS 218 Python CIS 218 Oakton Community College. CIS 218 Python features no compiling or linkingrapid development cycle no type declarationssimpler, shorter,
And PyLNP for the RCX By: Eric Cranmer and Nick Blake.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Lists in Python.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
H3D API Training  Part 3.1: Python – Quick overview.
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Built-in Data Structures in Python An Introduction.
Python The tutorial
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Python Functions.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Prof. Hilfinger CS164 Lecture 51 The Pyth Language Lecture 5.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
Lecture 4 Python Basics Part 3.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Introduction to Python Sajal Desai. What is Python? Versitile, simple, high level language No linking and compilation “By the way, the language is named.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Juancho Datu. What is a Module? File containing Python definitions and statements with the suffix ‘.py’ in the current directory For example file name:
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
27-Jan-1827-Jan-1827-Jan-1827-Jan-1827-Jan-1827-Jan-1827-Jan-1827-Jan-1827-Jan-18 Introduction.
Python’s Modules by E. Esin GOKGOZ.
Python Classes By Craig Pennell.
Topics Introduction to File Input and Output
Introduction To Python
Python’s Errors and Exceptions
4. sequence data type Rocky K. C. Chang 16 September 2018
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Topics Sequences Introduction to Lists List Slicing
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Python Primer 1: Types and Operators
By Ryan Christen Errors and Exceptions.
Topics Sequences Introduction to Lists List Slicing
Lecture 7: Python’s Built-in Types and Basic Statements
Topics Introduction to File Input and Output
Presentation transcript:

7-Sep-15 Python structure  modules: Python source files or C extensions  import, top-level via from, reload  statements  control flow  create objects  indentation matters – instead of {}  objects  everything is an object  automatically reclaimed when no longer needed

7-Sep-15 Basic operations  Assignment:  size = 40  a = b = c = 3  Numbers  integer, float  complex numbers: 1j+3, abs(z)  Strings  'hello world', 'it\'s hot'  "bye world"  continuation via \ or use """ long text """"

7-Sep-15 String operations  concatenate with + or neighbors  word = 'Help' + x  word = 'Help' 'a'  subscripting of strings  'Hello'[2]  'l'  slice: 'Hello'[1:2]  'el'  word[-1]  last character  len(word)  5  immutable: cannot assign to subscript

7-Sep-15 Lists  lists can be heterogeneous  a = ['spam', 'eggs', 100, 1234, 2*2]  Lists can be indexed and sliced:  a[0]  spam  a[:2]  ['spam', 'eggs']  Lists can be manipulated  a[2] = a[2] + 23  a[0:2] = [1,12]  a[0:0] = []  len(a)  5

7-Sep-15 Basic programming a,b = 0, 1 # non-zero = true while b < 10: # formatted output, without \n print b, # multiple assignment a,b = b, a+b

7-Sep-15 Control flow: if x = int(raw_input("Please enter #:")) if x < 0: x = 0 print 'Negative changed to zero' elif x == 0: print 'Zero' elif x == 1: print 'Single' else: print 'More'  no case statement

7-Sep-15 Control flow: for a = ['cat', 'window', 'defenestrate'] for x in a: print x, len(x)  no arithmetic progression, but  range(10)  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  for i in range(len(a)): print i, a[i]  do not modify the sequence being iterated over

7-Sep-15 Loops: break, continue, else  break and continue like C  else after loop exhaustion for n in range(2,10): for x in range(2,n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is prime'

7-Sep-15 Do nothing  pass does nothing  syntactic filler while 1: pass

7-Sep-15 Defining functions def fib(n): """Print a Fibonacci series up to n.""" a, b = 0, 1 while b < n: print b, a, b = b, a+b >>> fib(2000)  First line is docstring  first look for variables in local, then global  need global to assign global variables

7-Sep-15 Functions: default argument values def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik error' print complaint >>> ask_ok('Really?')

7-Sep-15 Keyword arguments  last arguments can be given as keywords def parrot(voltage, state='a stiff', action='voom', type='Norwegian blue'): print "-- This parrot wouldn't", action, print "if you put", voltage, "Volts through it." print "Lovely plumage, the ", type print "-- It's", state, "!" parrot(1000) parrot(action='VOOOM', voltage=100000)

7-Sep-15 Lambda forms  anonymous functions  may not work in older versions def make_incrementor(n): return lambda x: x + n f = make_incrementor(42) f(0) f(1)

7-Sep-15 List methods  append(x)  extend(L)  append all items in list (like Tcl lappend)  insert(i,x)  remove(x)  pop([i]), pop()  create stack (FIFO), or queue (LIFO)  pop(0)  index(x)  return the index for value x

7-Sep-15 List methods  count(x)  how many times x appears in list  sort()  sort items in place  reverse()  reverse list

7-Sep-15 Functional programming tools  filter(function, sequence) def f(x): return x%2 != 0 and x%3 0 filter(f, range(2,25))  map(function, sequence)  call function for each item  return list of return values  reduce(function, sequence)  return a single value  call binary function on the first two items  then on the result and next item  iterate

7-Sep-15 List comprehensions (2.0)  Create lists without map(), filter(), lambda  = expression followed by for clause + zero or more for or of clauses >>> vec = [2,4,6] >>> [3*x for x in vec] [6, 12, 18] >>> [{x: x**2} for x in vec} [{2: 4}, {4: 16}, {6: 36}]

7-Sep-15 List comprehensions  cross products: >>> vec1 = [2,4,6] >>> vec2 = [4,3,-9] >>> [x*y for x in vec1 for y in vec2] [8,6,-18, 16,12,-36, 24,18,-54] >>> [x+y for x in vec1 and y in vec2] [6,5,-7,8,7,-5,10,9,-3] >>> [vec1[i]*vec2[i] for i in range(len(vec1))] [8,12,-54]

7-Sep-15 List comprehensions  can also use if : >>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] []

7-Sep-15 del – removing list items  remove by index, not value  remove slices from list (rather than by assigning an empty list) >>> a = [-1,1,66.6,333,333,1234.5] >>> del a[0] >>> a [1,66.6,333,333,1234.5] >>> del a[2:4] >>> a [1,66.6,1234.5]

7-Sep-15 Tuples and sequences  lists, strings, tuples: examples of sequence type  tuple = values separated by commas >>> t = 123, 543, 'bar' >>> t[0] 123 >>> t (123, 543, 'bar')

7-Sep-15 Tuples  Tuples may be nested >>> u = t, (1,2) >>> u ((123, 542, 'bar'), (1,2))  kind of like structs, but no element names:  (x,y) coordinates  database records  like strings, immutable  can't assign to individual items

7-Sep-15 Tuples  Empty tuples: () >>> empty = () >>> len(empty) 0  one item  trailing comma >>> singleton = 'foo',

7-Sep-15 Tuples  sequence unpacking  distribute elements across variables >>> t = 123, 543, 'bar' >>> x, y, z = t >>> x 123  packing always creates tuple  unpacking works for any sequence

7-Sep-15 Dictionaries  like Tcl or awk associative arrays  indexed by keys  keys are any immutable type: e.g., tuples  but not lists (mutable!)  uses 'key: value' notation >>> tel = {'hgs' : 7042, 'lennox': 7018} >>> tel['cs'] = 7000 >>> tel

7-Sep-15 Dictionaries  no particular order  delete elements with del >>> del tel['foo']  keys() method  unsorted list of keys >>> tel.keys() ['cs', 'lennox', 'hgs']  use has_key() to check for existence >>> tel.has_key('foo') 0

7-Sep-15 Conditions  can check for sequence membership with is and is not : >>> if (4 in vec):... print '4 is'  chained comparisons: a less than b AND b equals c: a < b == c  and and or are short-circuit operators:  evaluated from left to right  stop evaluation as soon as outcome clear

7-Sep-15 Conditions  Can assign comparison to variable: >>> s1,s2,s3='', 'foo', 'bar' >>> non_null = s1 or s2 or s3 >>> non_null foo  Unlike C, no assignment within expression

7-Sep-15 Comparing sequences  unlike C, can compare sequences (lists, tuples,...)  lexicographical comparison:  compare first; if different  outcome  continue recursively  subsequences are smaller  strings use ASCII comparison  can compare objects of different type, but by type name (list < string < tuple)

7-Sep-15 Comparing sequences (1,2,3) < (1,2,4) [1,2,3] < [1,2,4] 'ABC' < 'C' < 'Pascal' < 'Python' (1,2,3) == (1.0,2.0,3.0) (1,2) < (1,2,-1)

7-Sep-15 Modules  collection of functions and variables, typically in scripts  definitions can be imported  file name is module name +.py  e.g., create module fibo.py def fib(n): # write Fib. series up to n... def fib2(n): # return Fib. series up to n

7-Sep-15 Modules  import module: import fibo  Use modules via "name space": >>> fibo.fib(1000) >>> fibo.__name__ 'fibo'  can give it a local name: >>> fib = fibo.fib >>> fib(500)

7-Sep-15 Modules  function definition + executable statements  executed only when module is imported  modules have private symbol tables  avoids name clash for global variables  accessible as module.globalname  can import into name space: >>> from fibo import fib, fib2 >>> fib(500)  can import all names defined by module: >>> from fibo import *

7-Sep-15 Module search path  current directory  list of directories specified in PYTHONPATH environment variable  uses installation-default if not defined, e.g.,.:/usr/local/lib/python  uses sys.path >>> import sys >>> sys.path ['', 'C:\\PROGRA~1\\Python2.2', 'C:\\Program Files\\Python2.2\\DLLs', 'C:\\Program Files\\Python2.2\\lib', 'C:\\Program Files\\Python2.2\\lib\\lib-tk', 'C:\\Program Files\\Python2.2', 'C:\\Program Files\\Python2.2\\lib\\site- packages']

7-Sep-15 Compiled Python files  include byte-compiled version of module if there exists fibo.pyc in same directory as fibo.py  only if creation time of fibo.pyc matches fibo.py  automatically write compiled file, if possible  platform independent  doesn't run any faster, but loads faster  can have only.pyc file  hide source

7-Sep-15 Standard modules  system-dependent list  always sys module >>> import sys >>> sys.p1 '>>> ' >>> sys.p2 '... ' >>> sys.path.append('/some/directory')

7-Sep-15 Module listing  use dir() for each module >>> dir(fibo) ['___name___', 'fib', 'fib2'] >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__st din__', '__stdout__', '_getframe', 'argv', 'builtin_module_names', 'byteorder', 'copyright', 'displayhook', 'dllhandle', 'exc_info', 'exc_type', 'excepthook', ' exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getrecursionlimit', ' getrefcount', 'hexversion', 'last_type', 'last_value', 'maxint', 'maxunicode', ' modules', 'path', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setpr ofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', 'winver']

7-Sep-15 Classes  mixture of C++ and Modula-3  multiple base classes  derived class can override any methods of its base class(es)  method can call the method of a base class with the same name  objects have private data  C++ terms:  all class members are public  all member functions are virtual  no constructors or destructors (not needed)

7-Sep-15 Classes  classes (and data types) are objects  built-in types cannot be used as base classes by user  arithmetic operators, subscripting can be redefined for class instances (like C++, unlike Java)

7-Sep-15 Class definitions Class ClassName:...  must be executed  can be executed conditionally (see Tcl)  creates new namespace

7-Sep-15 Namespaces  mapping from name to object:  built-in names ( abs() )  global names in module  local names in function invocation  attributes = any following a dot  z.real, z.imag  attributes read-only or writable  module attributes are writeable

7-Sep-15 Namespaces  scope = textual region of Python program where a namespace is directly accessible (without dot)  innermost scope (first) = local names  middle scope = current module's global names  outermost scope (last) = built-in names  assignments always affect innermost scope  don't copy, just create name bindings to objects  global indicates name is in global scope

7-Sep-15 Class objects  obj.name references (plus module!): class MyClass: "A simple example class" i = 123 def f(self): return 'hello world' >>> MyClass.i 123  MyClass.f is method object

7-Sep-15 Class objects  class instantiation: >>> x = MyClass() >>> x.f() 'hello world'  creates new instance of class  note x = MyClass vs. x = MyClass()  ___init__() special method for initialization of object def __init__(self,realpart,imagpart): self.r = realpart self.i = imagpart

7-Sep-15 Instance objects  attribute references  data attributes (C++/Java data members)  created dynamically x.counter = 1 while x.counter < 10: x.counter = x.counter * 2 print x.counter del x.counter

7-Sep-15 Method objects  Called immediately: x.f()  can be referenced: xf = x.f while 1: print xf()  object is passed as first argument of function  'self'  x.f() is equivalent to MyClass.f(x)

7-Sep-15 Notes on classes  Data attributes override method attributes with the same name  no real hiding  not usable to implement pure abstract data types  clients (users) of an object can add data attributes  first argument of method usually called self  ' self ' has no special meaning (cf. Java)

7-Sep-15 Another example  bag.py class Bag: def __init__(self): self.data = [] def add(self, x): self.data.append(x) def addtwice(self,x): self.add(x)

7-Sep-15 Another example, cont'd.  invoke: >>> from bag import * >>> l = Bag() >>> l.add('first') >>> l.add('second') >>> l.data ['first', 'second']

7-Sep-15 Inheritance class DerivedClassName(BaseClassName)...  search class attribute, descending chain of base classes  may override methods in the base class  call directly via BaseClassName.method

7-Sep-15 Multiple inheritance class DerivedClass(Base1,Base2,Base3):  depth-first, left-to-right  problem: class derived from two classes with a common base class

7-Sep-15 Private variables  No real support, but textual replacement (name mangling)  __var is replaced by _classname_var  prevents only accidental modification, not true protection

7-Sep-15 ~ C structs  Empty class definition: class Employee: pass john = Employee() john.name = 'John Doe' john.dept = 'CS' john.salary = 1000

7-Sep-15 Exceptions  syntax (parsing) errors while 1 print 'Hello World' File " ", line 1 while 1 print 'Hello World' ^ SyntaxError : invalid syntax  exceptions  run-time errors  e.g., ZeroDivisionError, NameError, TypeError

7-Sep-15 Handling exceptions while 1: try: x = int(raw_input("Please enter a number: ")) break except ValueError: print "Not a valid number"  First, execute try clause  if no exception, skip except clause  if exception, skip rest of try clause and use except clause  if no matching exception, attempt outer try statement

7-Sep-15 Handling exceptions  try.py import sys for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'lines:', len(f.readlines()) f.close  e.g., as python try.py *.py

7-Sep-15 Spectrum analysis  Spectrum analysis is the process of determining the frequency domain representation of a time domain signal:  Most commonly Discrete Fourier Transform (DFT) is used to determine the frequency content of signals  Fast Fourier Transform (FFT) is an efficient method for calculating the DFT.  Scipy implements FFT

7-Sep-15 Numpy & Scipy Things SPECIAL ARRAYS: linspace import numpy # import the array library numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) Examples: np.linspace(2.0, 3.0, num=5) array([ 2., 2.25, 2.5, 2.75, 3. ]) np.linspace(2.0, 3.0, num=5, endpoint=False) array([ 2., 2.2, 2.4, 2.6, 2.8]) np.linspace(2.0, 3.0, num=5, retstep=True) (array([ 2., 2.25, 2.5, 2.75, 3. ]), 0.25) myarray = numpy.linspace(0, 5, 10) print myarray [ ]

7-Sep-15 Numpy & Scipy Things SPECIAL ARRAYS : arange import numpy # import the array library numpy.arange([start, ]stop, [step, ]dtype=None) Examples: np.arange(3) array([0, 1, 2]) np.arange(3.0) array([ 0., 1., 2.]) np.arange(3,7) array([3, 4, 5, 6]) np.arange(3,7,2) array([3, 5])

7-Sep-15 Numpy & Scipy Things import numpy as np import matplotlib.pyplot as plt # import plotting library N = 8 y = np.zeros(N) x1 = np.linspace(0, 10, N, endpoint=True) x2 = np.linspace(0, 10, N, endpoint=False) plt.plot(x1, y, 'o') plt.plot(x2, y + 0.5, 'o') plt.ylim([-0.5, 1]) (-0.5, 1) plt.show()

7-Sep-15 Create Sound ( tone synthesis) from scipy.io.wavfile import write from numpy import linspace,sin,pi,int16 from pylab import plot,show,axis # tone synthesis def note(freq, len, amp=1, rate=44100): t = linspace(0,len,len*rate) data = sin(2*pi*freq*t)*amp return data.astype(int16) # two byte integers # A tone, 2 seconds, samples per second tone = note(440,2,amp=10000) write('440hzAtone.wav',44100,tone) # writing the sound to a file plot(linspace(0,2,2*44100),tone) axis([0,0.4,15000,-15000]) show()