Python source materials

Similar documents
Lecture 5: Python PYTHON

developed ~2007 by Robert Griesemer, Rob Pike, Ken Thompson open source

Advanced Programming Techniques. Python. Christopher Moretti

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

Advanced Python. Executive Summary, Session 1

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

Download Python from Any version will do for this class

Babu Madhav Institute of Information Technology, UTU 2015

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

CS Programming Languages: Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Introduction to Python (All the Basic Stuff)

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

Python. Executive Summary

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

DaMPL. Language Reference Manual. Henrique Grando

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

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

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

Some material adapted from Upenn cmpe391 slides and other sources

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

The Pyth Language. Administrivia

Python in 10 (50) minutes

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

Structure and Flow. CS 3270 Chapter 5

Python 1: Intro! Max Dougherty Andrew Schmitt

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Advanced Algorithms and Computational Models (module A)

Programming to Python

Computational Integer Programming. Lecture 4: Python. Dr. Ted Ralphs

Python: Short Overview and Recap

CS Advanced Unix Tools & Scripting

Senthil Kumaran S

Introduction to Python

Over-simplified history of programming languages

INTERPRETATION AND SCHEME LISTS 12

(CC)A-NC 2.5 by Randall Munroe Python

Table of Contents EVALUATION COPY

ENGR 102 Engineering Lab I - Computation

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

Awk. 1 What is AWK? 2 Why use AWK instead of Perl? 3 Uses Of AWK. 4 Basic Structure Of AWK Programs. 5 Running AWK programs

OCR Pseudocode to Python

CS 349 / SE 382 Scripting. Professor Michael Terry March 18, 2009

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Python Tutorial. Day 2

Flow Control: Branches and loops

Object Model Comparisons

Scripting languages. shell programs are good for personal tools

Course Title: Python + Django for Web Application

COP4020 Programming Assignment 1 - Spring 2011

Lecture no

Key Differences Between Python and Java

A Little Python Part 2

And Parallelism. Parallelism in Prolog. OR Parallelism

Scripting languages. shell programs are good for personal tools

Variable and Data Type I

Python debugging and beautification

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

GOLD Language Reference Manual

Large-Scale Networks

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

The current topic: Python. Announcements. Python. Python

Lecture 8 (7.5?): Javascript

18.1. CS 102 Unit 18. Python. Mark Redekopp

Overview of List Syntax

INTERPRETATION AND SCHEME LISTS 12

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

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

Try and Error. Python debugging and beautification

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Scheme as implemented by Racket

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Python for ArcGIS. Lab 1.

CIS192 Python Programming. Robert Rand. August 27, 2015

Introduction to Python! Lecture 2

Scheme: Strings Scheme: I/O

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

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

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

COMP-520 GoLite Tutorial

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

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

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Variable and Data Type I

EE 355 Unit 17. Python. Mark Redekopp

PTN-102 Python programming

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Evolution of Programming Languages

Introduction to Python

CS112 Spring 2012 Dr. Kinga Dobolyi. Exam 2. Do not open this exam until you are told. Read these instructions:

Python Class-Lesson1 Instructor: Yao

1 Lexical Considerations

APT Session 2: Python

CIS192: Python Programming

CSC Web Programming. Introduction to JavaScript

Transcription:

xkcd.com/353

Python source materials Bob Dondero s Python summary from Spring 2011 http://www.cs.princeton.edu/courses/archive/spring11/cos333/ reading/pythonsummary.pdf bwk s Python help file: http:// /cos333/python.help/ Official Python documentation: http://docs.python.org/tutorial/ http://docs.python.org/reference http://docs.python.org/library Idiomatic Python: http://python.net/~goodger/projects/pycon/2007/idiomatic/ handout.html Python challenge: http://www.pythonchallenge.com/

Python constructs constants, variables, types operators and expressions statements, control flow aggregates functions libraries classes modules etc.

Constants, variables, operators constants integers, floats, True/False! string, string, r, r, potentially multi-line string! no difference between single and double quotes r... is a raw string: doesn t interpret \ sequences within variables hold strings or numbers, as in Awk no automatic coercions; interpretation determined by operators and context no declarations variables are either global or local to a function (or class) operators mostly like C, but no ++, --,?:! relational operators are the same for numbers and strings string concatenation uses + format with fmt string % (list of expresssions)!

Statements, control flow statements assignment, control flow, function call, scope indicated by [consistent] indentation; no terminator or separator control flow if condition: try:! statements statements! elif condition: except:! statements statements! else:! statements! while condition:! statements! for v in list:! statements! [break, continue to exit early]

Exception example import string! import sys! def cvt(s):! while len(s) > 0:! try:! return string.atof(s)! except:! s = s[:-1]! return 0! s = sys.stdin.readline()! while s!= '':! print '\t%g' % cvt(s)! s = sys.stdin.readline()!

Lists list, initialized to empty food = [] list, initialized with 3 elements: food = [ 'beer', 'pizza', "coffee" ] elements accessed as arr[index] indices from 0 to len(arr)-1 inclusive add new elements with list.append(value) : food.append('coke') slicing: list[start:end] is elements start..end-1 example: echo command: for i in range(1, len(sys.argv)): if i < len(sys.argv): print argv[i], #, at end suppresses newline else: print argv[i] tuples are like lists, but are constants soda = ( 'coke', 'pepsi' ) soda.append('dr pepper') is an error

Dictionaries (== associative arrays) dictionaries are a separate type from lists subscripts are arbitrary strings elements initialized with dict = {'pizza':200, 'beer':100} accessed as dict[str] example: add up values from name-value input pizza 200 beer 100 pizza 500 coke 50 import sys, string, fileinput val = {} # empty dictionary line = sys.stdin.readline() while line!= : (n, v) = line.strip().split() if val.has_key(n): val[n] += string.atof(v) else: val[n] = string.atof(v) line = sys.stdin.readline() for i in val: print "%s\t%g" % (i, val[i]) AWK version: { val[$1] += $2 } END { for (i in val) print i, val[i] }

Functions def name(arg, arg, arg): statements of function def div(num, denom): ''' computes quotient & remainder. denom should be > 0''' q = num / denom r = num % denom return (q, r) # returns a list functions are objects can assign them, pass them to functions, return them from fcns parameters are passed call by value can have named arguments and default values and arrays of name-value pairs variables are local unless declared global EXCEPT if you only read a global, it's visible x = 1; y = 2 def foo(): y=3; print x,y foo() 1 3 print y 2

Function arguments positional arguments def div(num, denom):! keyword arguments def div(num=1, denom=1):! must follow any positional arguments variable length argument lists * def foo(a, b=1, *varlist)! variable length argument must follow positional and keyword args additional keyword arguments ** def foo(a, b=1, *varlist, **kwords)! all extra name=val arguments are put in dictionary kwords

Regular expressions and substitution underlying mechanisms like Perl: libraries, not operators, less syntax re.search(pat, str) find first match re.match(pat, str) test for anchored match re.split(pat, str) split into list of matches re.findall(pat, str) list of all matches re.sub(pat, repl, str) replace all pat in str by repl shorthands in patterns \d = digit, \D = non-digit \w = "word" character [a-za-z0-9_], \W = non-word character \s = whitespace, \S = non-whitespace \b = word boundary, \B = non-boundary substrings matched parts are saved for later use in \1, \2,... s = re.sub(r'(\s+)\s+(\s+)', r'\2 \1', s) flips 1st 2 words of s watch out re.match is anchored (match must start at beginning) patterns are not matched leftmost longest

Classes and objects class Stack: def init (self): # constructor self.stack = [] # local variable def push(self, obj): self.stack.append(obj) def pop(self): return self.stack.pop() # list.pop def len(self): return len(self.stack) stk = Stack() stk.push("foo") if stk.len()!= 1: print "error" if stk.pop()!= "foo": print "error" del stk always have to use self in definitions special names like init (constructor) information hiding only by convention; not enforced

Modules a module is a library, often one class with lots of methods core examples: sys argv, stdin, stdout string find, replace, index, re match, sub, os open, close, read, write, getenviron, system, fileinput awk-like processing of input files urllib manipulating url s

Review: Formatter in AWK /./ { for (i = 1; i <= NF; i++) addword($i) } /^$/ { printline(); print "" } END { printline() } function addword(w) { if (length(line) + length(w) > 60) printline() line = line space w space = " " } function printline() { if (length(line) > 0) print line line = space = "" }

Formatter in Python (version 1) import sys, string line=""; space = "" def main(): buf = sys.stdin.read() for word in string.split(buf): addword(word) printline() def addword(word): global line, space if len(line) + len(word) > 60: printline() line = line + space + word space = " " def printline(): global line, space if len(line) > 0: print line line = space = "" main()

Formatter in Python (comparing input styles) def main(): buf = sys.stdin.read() for word in string.split(buf): addword(word) printline() def main(): buf = sys.stdin.readline() while buf!= "": if len(buf) == 1: printline() print "" else: for word in string.split(buf): addword(word) buf = sys.stdin.readline() printline()

Surprises, gotchas, etc. indentation for grouping, ":" always needed no implicit conversions often have to use class name (string.atof(s)) elif, not else if no ++, --,?: assignment is not an expression no equivalent of while ((c = getchar())!= EOF) % for string formatting global declaration to modify non-local variables in functions no uninitialized variables if v!= None: if arr.has_key(): regular expressions not leftmost longest re.match is anchored, re.sub replaces all

What makes Python successful? comparatively small, simple but rich language regular expressions, strings, tuples, assoc arrays clean (though limited) object-oriented mechanism reflection, etc. efficient enough seems to be getting better large set of libraries extensible by calling C or other languages embeddings of major libraries e.g., TkInter for GUIs open source with large and active user community standard: there is only one Python but watch out for Python 3, which is not backwards compatible a reaction to the complexity and irregularity of Perl?