New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Programming Languages and Compilers

by: Mr. Hayley Barton

Programming Languages and Compilers COMPSCI 164

Mr. Hayley Barton

GPA 3.93

P. Hilfinger

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

P. Hilfinger
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 44 page Class Notes was uploaded by Mr. Hayley Barton on Thursday October 22, 2015. The Class Notes belongs to COMPSCI 164 at University of California - Berkeley taught by P. Hilfinger in Fall. Since its upload, it has received 19 views. For similar materials see /class/226656/compsci-164-university-of-california-berkeley in ComputerScienence at University of California - Berkeley.


Reviews for Programming Languages and Compilers


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/22/15
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 P N Hil nger Spring 2008 The Pyth Programming Language V 32 Our project this year is a compiler for a dialect of the popular language PYTHON PYTHON itself is usually categorized as a scripting language meaning either that it is intended to imple ment extensions to your computer s command language or that it is intended to implement glue programs that accomplish most of their work by invoking other self contained pro grams You will often hear PYTHON described as an interpreted language in contrast to a compiled language To the limited extent this statement is meaningful it is false First as you ll see in this course the adjectives interpreted and compiled do not properly modify programming languages but rather implementations of programming languages Any language that can be implemented by an interpreter can be compiled and viceversa There are C compilers C interpreters Lisp compilers Lisp interpreters Java compilers and Java interpreters There indeed are PYTHON interpreters but this semester we will implement a compiler for the PYTH dialect of PYTHON Although this document is self contained I think that any well trained professional pro grammer would do well to be familiar with PYTHON itself a useful language whose design is refreshingly cleaniin marked contrast to other scripting languages especially PERL A reference document is available on line there is a link from the class homepage or in book form David M Beazley Python Essential Reference Third Edition New Riders Publishing 2006 ISBN 0672328623 1 Lexical Structure Typically we factor the description a programming languages syntax into two parts a lexical description which de nes a set of possible tokens or atomic symbols formed from the text of a program called its source code or source and a grammar that describes the possible properly formed constructs or sentences that may be created from sequences of such tokens It is not essential to make this separation but the practice has proven useful over the years and there are tools and techniques for converting each of these descriptions into translation programs The Pyth Programming Language v 32 2 11 Comments Whitespace and Ends of Lines The source code of a PYTH program consists of the tokens described below possibly inter spersed with whitespace blanks tabs formfeeds blank lines and comments Notionally the conversion of source into tokens proceeds from the beginning to the end of the source in sequence at each point forming the longest token or separator allowed by the rules For example the empty program print 42 is interpreted as a blank line consisting of a single comment and the end of line even though print and 42 can otherwise be interpreted as valid tokens Likewise if42 31 is treated as three tokens if42 and 31 even though if 42 3 and 1 could all be valid tokens This interpretation is sometimes called the mammal munch rule An implication of this is that whitespace between two tokens is necessary only when the two tokens could be interpreted differently if concatenated A comment consists of the hash character sometimes called an octothmpe followed by all characters up to but not including the end of the line A blank line consists of any amount of whitespacel possibly followed by a comment and the end of the line The end of a line is itself a token or part of one that is in contrast to most programming languages it is not generally treated as whitespace but as a terminating character like the semicolon in C or Java There are three exceptions 1 A backslash immediately followed by the end of a line and not inside a comment or string is treated as a space so that backslash acts as a continuation character 2 Inside a pair of balanced bracketing tokens and and or and J ends of lines are treated as spaces 3 Inside triple quoted string literals 56 end of line characters are treated as them selves For example the two statements print 12 13 print 12 13 are equivalent as are 3bcxi 3b cx l Hmm 1I m speaking formally here so when I say any amount77 I really mean any amount including zero The Pyth Programming Language v 32 3 12 Indentation PYTH and PYTHON are unusual among programming languages in that their statement bracketing construct uses indentation You are probably familiar with how other conven tional programming languages group multiple statements together into what are effectively single statements with brackets such as Pascal s begin end or C s and Java s ln PYTH there are two special opening and closing brackets often called INDENT and DE DENT which are supposed to balance each other like braces in Java Any non blank line that is indented by more than the last non blank line if any is treated as if it started with an INDENT token If a non blank line is indented by less than the previous non blank line then it is treated as if it started with one DEDENT token for each unbalanced INDENT token on a preceding line with the same or more indentation It is a syntax error if there is no preceding unbalanced INDENT on a line with the same indentation So for example if x print 1 Begins with INDENT if y print 2 Begins with INDENT Blank line ignored else Begins with DEDENT print 3 Begins with INDENT print 4 Begins with DEDENT DEDENT On the other hand this program is illegal if x print 1 print 2 Error inconsistent indentation To avoid special cases at the beginning and end the program is treated as if it started and ended with a completelx unindented pass t t For purposes of determining the amount a line is indented a horizontal tab character is equivalent to the smallest non zero number of spaces that causes the indentation of the current line so far to be a multiple of eight spaces Thus zero to seven spaces followed by a tab is equivalent to eight spaces The indentation of continuation lines is ignored that is it s treated as ordinary whitespace and not considered in inserting implicit lNDENTs and DEDENTs Thus if x print 1 x 3 y 4 is perfectly legal 21 have it on good authority that this design was the choice of Mrs Karin Dewar the nonprogramming wife of Prof Robert B K Dewar of NYU s Courant Institute when she was called in to mediate in her nightgown by the designers of PYTHON S ancestor language who could not agree on which of several alternative constructs to use The Pyth Programming Language V 32 4 13 Identi ers and Reserved Words An identi er is a token that consists of letters digits and underscores and does not start with a digit Identi ers are mostly used as names of things However certain of them have special roles in the syntax and may not be used as names These reserved words are as follows and elif global or assert else if pass break except import print class exec in raise continue finally is return def for lambda try del from not while Words marked with an asterisk are not used in PYTH but are reserved because of their use in PYTHON 14 Literals A literal is any construct that stands for a value determined entirely by the text of that literal For example the numeral 42 stands for an integral value that can be determined from its two digits in the usual way 141 Integer literals PYTH s integer literals are essentially the same as those of Java 0 A sequence of digits that does not start with 0 and is in the range 02147483648 is a decimal numeral The numeral 2147483648 represents the value 72147483648 due to PYTH s Java like modular arithmetic3 o A sequence of digits that starts with 0 represents an octal numeral and must be in the range 023271 0377777777778 Octal numerals greater than 23171 represent negative numbers as in Java for example 37777777777 represents 1 since 71 E 232 71 mod 232 o A token of the form OxH or OXH where H is a sequence of one or more hexadecimal base 16 digits 079 aif AiF represents a hexadecimal numeral H must be in the range 0232 7 1 0ffffffff16 As for octal literals numerals greater than 231 7 1 represent negative numbers 3You might ask why I didn t simply make 2147483647 the largest decimal numeral as in other languages since that is the largest positive integer representable in PYTH The reason is that such a rule makes it awkward to write the most negative number In PYTHas in Java there are no negative numerals just positive numerals that have the negation operator applied to them 4 is actually two tokens With the PYTH rule you ma write the most negative number as 2147483648 if you want since in modulo 232 arithmetic 2147483648 is its own negative The Pyth Programming Language V 32 5 142 Floatingpoint literals A oating point literal is a decimal fraction or a numeral in modi ed scienti c notation ln ordinary mathematical or engineering contexts such literals would denote rational numbers in PYTH they represent rational approximations to these numbers They are approximate in general because computer oating point arithmetic generally uses binary fractions internally and not all base 10 fractions can be exactly represented with nite base2 fractions For example 01 in base 2 is the repeating numeral 000011001100110011 and if oating point numbers are limited to 52 bits of signi cance a common number then what you write as 01 is actually 009999999999999997779553950749686919152736663818359375 which is close enough for most purposes Floating point literals in PYTH come in any of the following forms the following all denote the same number 1230 123 123e2 Means 123 x 102 123E2 0123e3 123e3 12300e1 1230e1 That is either a sequence of digits containing one decimal point or a sequence of digits containing at most one decimal point followed by an e or E an optional sign and an integer numeral which is always treated as decimal 143 String literals Strings in PYTH are sequences of bytes Their literals are written as ASCII text surrounded by any of several different kinds of quotation marks Literal Meaning quotA string in double quotesquot A string in double quotes A quotstringquot in single quotes A quotstringquot in single quotes quotA quotstringquot in double quotesquot A quotstringquot in double quotes A string in single quotes A string in single quotes A string in triple single quotes A string in triple single quotes quot quot quotA quotstringquot in triple double quotesquot quot quot A quotstringquot in triple double quotes quotA stringnthat contains a new linequot A string that contains a new line A multiline A multiline string in triple single quotes string in triple single quotes quot quot quotA multiline A multiline string in triple double quotesquot quot quot string in triple double quotes The Pyth Programming Language V 32 6 As these examples suggest string literals generally represent the literal sequence of characters composing them minus the matching beginning and ending quotes which may be any of the symbols double quote single quote triple double quote triple single quote The exceptions are the following two character escape sequences each of which denotes a single character a Bell ControlG encoded as the byte value 7 b Backspace ControlH byte value 8 t Tab ControlI byte value 9 n New line ControlJ byte value 10 r Return ControlM byte value 13 e Escape byte value 27 O Null byte value 0 v Vertical tab byte value 11 f Form feed ControlL byte value 12 quot Double quotation mark Single quotation mark apostrophe Backslash lnside single quotes the double quote need not be escaped and inside double quotes the single quote need not be escaped Triple quoted strings may contain newlines whereas their singlequoted counterparts may not and have to use n instead All strings end at the rst occurrence of an unescaped matching quote Thus quotquotquotquotquotxquotquot quotquotquot means quotquotxquotquot An unrecognized escape sequenceia backslash followed by any character other than those abovei is unchanged so q represents the sequence q A raw string is a string literal pre xed with r or R In these strings all backslash sequences are treated as unrecognized escape sequences Thus r n represents the two character string n and r represents there is no way to write a raw string literal that ends in a single backslash Finally two adjacent string literals separated if at all only by whitespace represent the concatenation of the two strings Thus quotOnequot quotStringquot represents One String quot exonquot quot erate quot represents exonerate quotUse quot r n for newline represents Use n for newline rquotPuts a after raw stringquot represents Puts a after raw string 2 Statements A statement is a language construct that does somethingquot This is as opposed to an expres sion which is a language construct that denotes a value or a computation that produces a value Statements and expressions are closely related and some expressions can double as statements they are evaluated for their side effectsquot as opposed to their values We often simple t from mp i39 391 t t t The latter contain other state ments so that their syntactic de nition is therefore generally recursive A control statement The Pyth Programming Language v 32 7 is a kind of statement that controls when and whether other statements are executed A declaration is a kind of statement that de nes new names A statement per se consists either of a statement list a single compound statement a single import statement 25 or a type declaration 42 A statement list is a sequence of one or more simple statements separated by semicolons optionally followed by a semicolon and then terminated by a newline The simple statements are pass 211 print statements 213 e piession t 212 214 and 215 break and continue statements 232 and return statements 24 A program in PYTH consists of a sequence of zero or more statements 21 Noncontrol statements 211 Pass A pass statement does nothing This probably does not sound useful but one does occasion ally need to write for example a statement that doesn t need to do anything in places where PYTH requires there to be a statement def close 1 pass or you just might think that it looks better to be explicit about cases in which nothing needs to happen if x lt 0 pass elif x lt 10 y f x elif 212 Expression statements Any non empty expression list see 54 may be used as a statement as may an empty pair of parentheses although as a statement it is entirely useless When used as a statement its value is ignored and the expressions are evaluated for their side effects alone So typically you ll see function calls like this clear theBoard 213 Print A print statement is a convenient way to output text The simple form print expressionl expressionk prints external representations of its arguments separated by spaces on the standard output followed by an end of line If k 0 therefore as in The Pyth Programming Language v 32 8 print the program simply starts a new line The external representations used are those produced by the str method which is de ned on all types 41 Following the last expression with a comma print expressionl expressionk k 2 1 does the same thing but suppresses the end of line For all but the rst output on a line furthermore both forms of print rst output a space As a result print 1 print 2 print 3 prints 1 2 3 just like print 1 2 3 You can direct output to a le other than the standard output using the gtgt operator f open quotresultstxtquot quotrquot f points to a quotfile objectquot print gtgt f quotThe answer isquot x Again in the absence of arguments this just ends the current line in f and with a trailing comma it suppresses the end of line The standard output is represented by a le called sys stdout so that the following are equivalent print 1 2 3 print gtgtsysstdout 1 2 3 The le sys stderr represents the standard error output conventionally used for error mes sages from the program 214 Assignment In its simplest form an assignment looks like this variable expression The value of the expression is stored in the variable The right side of an assignment may be a list of expressions separated by commas and possibly followed by one which is just an abbreviation for a tuple see 54 x1 2 3 short forx1 2 3 371 short fory 1 The Pyth Programming Language v 32 9 cause x to reference the tuple 1 2 3 and y to reference the oneelement tuple 1 The left side of an assignment must be something assignable to an lualue in CC parlance This can mean a simple variable or parameter as in the examples above It can also be a dereferenced eld of an object as in x Account 0 x now references an object of type Account xbalance 0 an indexed element of a list as in A 1 2 3 A2 4 The list now contains 1 2 4 or a slice of a list see also 53 as in A 1 2 3 4 A1z3 5 6 The list now contains 1 5 6 4 A34 The list now contains 1 5 6 AOzo 1 O The list now contains 1 O 1 5 6 ASz 9 Same as ASz5 9 the list now contains 1 O 1 9 Actually these last cases are themselves a shorthand syntactic sugar 4 Assignment l Meaning A1 E 11setitemA1E A34 S 11setsliceA 3 4 S Things get interesting when the left side of an assignment is a tuple of assignable entities In this case the value on the right side must itself reference a value that can be treated as a sequence tuple list dictionary with the same number of elements A simple example 1 2 3 Equivalent to x y z 1 2 3 2 3 Same thing which assigns 1 2 and 3 respectively to x y and z The right side of the assignment need not be an explicit sequence as long as its value is a sequence at execution time For example q 1 2 3 x y z q has the same effect on x y and 2 as the previous assignments To distinguish a oneelement sequence on the left side from a simple assignment use a trailing comma x 1 4Slyntactz39c sugar refers to builtin language syntax that is equivalent to some less convenient or less familiar form Thus We say that A1 is syntactic sugar77 for or is the sugared Version of77 or is sugaring of77 quotgetWOK 1 This usage has led some to use the term syntactic alum77 for distasteful attempts at syntactic sugaring or from Brian Reid syntactic ketchup77 for unnecessary sugaring The Pyth Programming Language v 32 10 assigns the integer 1 to x while x 1 assigns the oneelement sequence containing the single element 1 to x In general one may always have a trailing comma after a list of things forming some kind of sequence display but it only makes a difference in the one element case The left side sequences may be nested as in x y z3 q which requires that q contain two elements the second of which is a sequence containing two items 215 Augmented assignments As in Java the augmented assignment operators etc have the effect of applying an operator to a variable s value and then assigning the result back into the same variable For example x fx is equivalent to x x fx Unlike Java however Pyth restricts the use of the augmented assignments to simple variables We don t allow AO 1 We also do not allow x y 17 That is the right hand side of an augmented assignment must be a simple expression not an assignment statement Because of these restrictions we can translate all augmented assign ments into equivalent simple assignments Thus x fx becomes xxfx The Pyth Programming Language v 32 11 22 Grouping statements in i ii i a A A 11 Compound statements by de nition contain smaller My each of these constituents is a statement but one often needs the effect of a sequence of statements rather than just one Typical programming languages provide some kind grouping or block construct for this purpose In PYTH this construct is called a suite which comes in two avors The rst form of suite is the statement list For example if h gt 0 dx xh dy yh else print singularity The second form consists of an end of line followed by an lNDENT see 12 one or more statements each terminated by an end of line and a matching DEDENT For example ifhgt0 dxxh dy yh else print quot singularityquot In a statement like this with two suites there is no need to use the same form for both for example ifhgt0 dxxh dy yh else print singularity 23 Control statements 231 Ifstatements This statement executes exactly one of several possible statements depending on the values of some condition tests The general form is if expressionl suitel elif expressiong suiteg elif expressionk suitek else suitekll where k 2 1 so that there need not be any elif clauses and the else clause is optional A missing else clause is equivalent to else pass Each expression is evaluated in order The suite corresponding to the rst expression that yields a true value see 513 is executed after which the whole if statement is nished If no expression yields a true value the else clause is executed The Pyth Programming Language v 32 232 While break and continue statements The while statement executes a body repeatedly under control of an iteration condition while expression suitel else suiteg This repeatedly evaluates expression and executes suitel as long as the expression yields a true value see 513 When the expression yields a false value suiteg is executed The else clause is optional and when missing defaults to else pass The control statement break terminates execution of the nearest enclosing loop that contains the break in its loop body suitel for while loops and that is also contained inside the same class or function de nitions if any that immediately encloses the break statement It is an error for break to appear anywhere else For example these breaks are illegal def f n if c gt 0 break ERROR not in a loop while True def test x if x gt 0 break ERROR def test intervenes Execution of break skips the else clause of the loop it terminates For example 11 0 while 11 lt len A if An X break else return None print 11 prints the index at which X occurs in A or returns a null value from whatever function contains this code The control statement continue may only occur where break may occur lts effect is to skip to the end of the current iteration of the loop body For example while i lt Nl if Ai 0 continue print quotComputing A od quot 70 i Ai fi The Pyth Programming Language v 32 13 skips the print and assignment statements if A i is not 0 The break and continue statements are also valid inside for loops7 described next 233 For loops The for loop is simply a shorthand for a particular kind of while loop5 You write for umiable in expression list suitel else suiteg This is functionally equivalent to the following LST expression list I 0 while I lt len LST umiable getindex LST I I 1 suitel but indented appropriately else suiteg where LST and I are replaced by some new variables that are not used anywhere else in the program As usual7 the else clause may be omitted7 in which case suiteg defaults to pass For example A1 23 Anarray for i in A print i The getindex method is de ned for built in sequence types and programmers can de ne this method for new classes as well just as Java programmers can de ne classes that implement javautilIterable and work with Java s for loop PYTH has a built in type xrange that allows you to write loops over numbers for i in xrange 03 print i prints 0 1 2 ln effect7 the value of xrangeltL7 U is the sequence of integers7 j such that L g j lt U 24 Return statements The statement return optionaliexpressionilist must be a part of a function body The erpressionJist defaults to None if not speci ed It is evaluated and this value is returned as the value of the current call to the innermost enclosing function 5PYTH S for statement di ers signi cantly from PYTHOle7 which makes use of generators and exceptions The Pyth Programming Language v 32 14 25 Import statements The statement import identi er causes the contents of a le called identi erpy to be substituted for the statement if that le has not previously been imported The statement has no effect if identi erpy has already been imported It may only occur at the outer level of the program and not within a suite including those of class declarations or function declarations The compiler searches for this le in the directory containing the program s source plus additional directories in a standard list At the end of a indenti erpy all open lNDENT brackets are implicitly closed with DEDENTS as if the le were followed by an unindented pass statement 3 Scoping and Declarations In the study of programming languages a declaration is something that introduces a meaning or binding for an identi er See 6 for information about declaring classes This section discusses the other kinds of declaration 31 Scopes and declarative regions The scope of a declaration is the segment of program text or execution in which that decla ration s binding is the one that de nes the identi er PYTH uses static scoping which means that the scope of a declaration is xed and does not depend on what statements in the pro gram get executed A declarative region is a section of text that con nes the scope of the declarations within it For example in the Java declaration class A 0 private int x 1 void f int x 2 if x gt 0 3 int y 4 f y 5 else 6 String y 7 g y 8 9 voingi 10 11 there are declarative regions for the body of A lines 1710 the body of f lines 278 the block that forms the then part of the if statement lines 475 and the block that forms the The Pyth Programming Language v 32 15 else clause lines 778 The scope of the declaration of y at 4 is lines 475 beginning at the declaration and ending with the declarative region that contains that declaration The scope of the declaration of y at 7 is lines 778 The scopes of the declaration of f and g are line 1710 of A plus certain locations elsewhere following a 7 as in qf 3 The scope of the declaration of x at 1 is lines 1 and 9710 the hole in the middle is caused by the fact that the declaration of x at 2 hides or shadows the declaration at 1 ln PYTH the declarative regions are the program as a whole plus the body of each class and the parameter list and body together of each function de nition The scope of a declaration that appears immediately inside a class declaration is the body of that class declaration not including bodies of functions de ned inside the class plus places where the declaration is made visible by selection see 61 The scope of other declarations extends throughout the entire declarative region that immediately enclose them For example in def f x y while x gt 0 if y print 2 A else 2 x1 B xgz C y 1 defgy D the local variable 2 is created by the assignment statement B and is the same variable referred to in A The function g referred to at C is the same one de ned at D No name may be given two declarations immediately within the same declarative region Local variable declarations parameter declarations and defs may be hidden in nested declar ative regions For example with def f x 3 def g x print x g12 a call to f prints 12 Names of types prede ned or otherwise may not be redeclared anywhere in any declar ative region 32 Local variables Local variables are declared in a given declarative region if there are any assignments to them possibly implicit and they are not formal parameters of the immediately enclosing function Multiple assignments in the same declarative region count as one declaration For example in the following PYTH program x is local to the body of f y is a formal parameter the The Pyth Programming Language v 32 16 assignment to it does not create a new variable and SIZE is local to the program as a whole def f y y gltygt x y12 print y SIZE 13 The declaration in other words is implicit The scope of a local declaration of x includes the entire body of the declarative region containing it Thus when a variable is not assigned to in a particular declarative region its de nition is inherited although not in the object oriented sense from the enclosing context For example def f z x y 3 def g z y f prints 12 7 12 3 Sometimes however you mean for an assignment within a function body to refer to an outer variable The global declaration allows you to do so to a limited extent x 12 def tryToSetIt y X Y def reallySetIt y global x x tryToSetIt 42 print x Prints 12 reallySetIt 42 print x Prints 42 The identi ers there may be a comma separated list in a global declaration must be de ned at the outer level of the program ie outside any 1er or class declarations The scope of the global declaration is the entire function that contains it not including any nested function de nitions A global declaration at the outer level is rather useless but it does still require that its variables be de ned somewhere at the outer level It follows that a function can only set its own local variables or those at the outer global level If it is nested inside another function it cannot set that outer function s variables The The Pyth Programming Language v 32 17 reason is simple either the variable it assigns to is declared global in which case it refers to an outer level variable or else is declared local by the assignment itself The scope of a local variable declaration is the entire declarative region in which it is assigned to at least once Hence it is possible to reference the variable before its assignment Prior to assignment its value is None6 33 Declaring constants The declaration def name expression is a constant declaration that de nes name to denote the value of the expression The expres sions in constant declarations are evaluated in the usual execution order as if each declaration were an ordinary statement The scope of the name however will typically start before that in accordance with the usual scoping rules Prior to executing the declaration the value of name is None One cannot assign to anything de ned with def 34 Declaring functions and formal parameters Functions may be declared with function declarations which are specialized def statements as in def f x return x1 The identi ers listed in parentheses are the formal parameters of the function being de ned Their scope is the body of the function Functions declared this way immediately inside a class body are instance methods which means that they get called in a special way see 510 Preceding the declaration with the keyword class as in class def g 1 return 42 de nes a class method or static method which is basically just an ordinary function See 6 for the signi cance of class def which is used inside classes only It is also possible to de ne variables or ordinary constants whose values are functions to pass functions as parameters return them as values or store them in other data structures For example def f x y def synonymForF f functionVar f typedFunctionVar All All gt All typedFunctionVar f listOfFunctions synonymForF 6This treatment is di erent from Python s mostly to avoid introducing still another kind of Value the unde ned value77 The Pyth Programming Language v 32 18 35 Importing foreign functions PYTH programs can de ne functions implemented in foreign languages generally C by using a special import statement as the sole constituent of their body def Pyth name parameter list import quotforeign namequot The foreign name string must be a name recognizable to the linker Calls to function Pyth name will call the given foreign function passing the indicated parameters The precise calling conventions are implementation dependent 4 Values and types As for most programming languages every value manipulated in PYTH has a type These types are part of a hierarchy as in Java and each has a written denotation The prede ned types are described in Table 1 A type may be a subtype of another the inverse relation is supertype The subtype relation is re exive each type is a subtype of itself transitive all my supertypes are supertypes of my subtypes as well and antisymmetric if T is a subtype of T and viceverse then T T All types are subtypes of Any and Void is a subtype of all types so that the hierarchy properly speaking is what is known as a lattice All class types see 6 are subtypes of their declared parent types and of Object A function type T1 Tn gtT0 is only a subtype of Any and of any other function type T T gtT6 where T0 is a subtype of T6 and for every i T is a subtype of T yes that s right it s reversed for the arguments We say that subtyping in covariant in the return type and contrauariant in the argument types The other prede ned types in Table 1 have no other subtypes or supertypes Values in PYTH as in Java are generally references to objects These objects are ei ther immutableimeaning that once created their contents state may not be changedior mutable For example since list objects are mutable and tuple objects are not L Q L L1 O Legal L and Q now both reference the same list object with contents 103 T 1 2 3 T1 O Runtime error 123 However the sequence of assignments T 1 2 R T T 3 4 Legal R now references a tuple object with contents 12 and T references one with contents 34 7Actually most of PYTH s prede ned functions are themselves foreign code and use these special imports The Pyth Programming Language v 32 19 Table 1 Prede ned types in PYTH Name Any Void Object lnt Float Bool String Tuple Xrange List Dict File T17 7Tk gtT0 Description The supertype of all types Every value is an Any The type of the null object7 None A supertype of all user de ned classes Signed7 32 bit integers in the range 7231 to 231 7 1 Doubleprecision oating point numbers Logical values True or False Character strings lmmutable tuples eg7 1 2 3 Results of the xrange function ranges of lnts Mutable modi able sequences eg7 1 23 Mapping eg7 1 A 2 B External les The type of all functions that take k 2 0 arguments of types T17 Tk and returns a value of type To Notationally7 gtT0 defaults to gtVoid if omitted The Pyth Programming Language v 32 20 Again this is because as in Java the variable T contains a reference to these tuple objects The second assignment to T does not change the rst tuple s state it merely changes which tuple T is pointing to By their nature immutable objects have an interesting property one can pretend that their variables do not contain references to objects and instead contain the objects themselves After all as the examples above show after T is assigned to R there is nothing you can do T that changes the contents of the tuple pointed to by R just as in ordinary Java once you assign one integer variable to another any operations on the rst variable have no effect on the second In typical PYTH implementations we take advantage of this fact so that Int and Float valued variables for example do not contain pointers and doing arithmetic does not require allocating new object storage 41 The types Any and Void The special value None belongs to all types lts type is Void the subtype of all types In effect this type inherits all instance methods including ones in new classes you de ne provides implementations for a few and implements all the rest to cause errors All values belong to type Any it is a supertype of all types but one cannot create a value whose dynamic type is Any The methods de ned for Any include all the prede ned methods but with certain exceptions shown in Table 2 the default implementations of all these methods is to cause an errors 42 Declaring types A type declaration has the form name type It applies to the declaration of name variable constant function that is immediately within the current declarative region The given type becomes the static type of name wherever the declaration applies lf name is a variable or eld only values that have a subtype of the given type may be assigned to name The types of the formal parameters of a function may be declared outside the function like this augment Int Int gt Int def augment a b which causes a and b to have static type Int In the absence of an explicit type declaration functions declared with function declarations see 34 8This is in marked contrast to Java where for example the prede ned String methods are de ned only on Strings and will give compiletime errors when attempted on things whose static type is Object As a result of PYTH s rule many errors that would be caught at compiletime in Java are only caught during execution in PYTH The reason for this is to increase the resemblance between PYTH and its parent language PYTHON which is entirely dynamically typed New method names de ned by the user in PYTH by contrast are not de ned in class Any and so unlike PYTHON but like Java you need type declarations to inform the compiler that these new method exist in a particular Value The Pyth Programming Language v 32 21 def fa1an have type Any Any gtAny for non instance methods and TAny Any gtAny for instance methods where T is the enclosing class name see 6 In either case there are n argument types All other declarations by default ascribe a static type of Any to the declared entity 43 Static type consistency The PYTHON language is dynamically typed meaning that at execution time each value carries with it information that identi es its type It is possible for a program to specify an operation on a certain variable that turns out to be meaningless when actually executed because the particular value of that variable happens to have the wrong type at the time Java by contrast is statically typed meaning that at translation time and apart from any execution the compiler has enough information to know whether there might be type errors upon execution and rejects programs where this is the case PYTH is a sort of compromise It is statically typed but the default implementation of many operations is to raise an error This allows many PYTHON programs to run pretty much unchanged in PYTH but at the time it weakens the compiletime error detection that PYTH can do relative to languages such as Java or C PYTH s dynamic type rule enforced at execution time if necessary is basically that the actual value assigned to any variable attribute parameter or constant or returned from any function must have a subtype of the static type declared for that variable attribute etc lts static type rule enforced by the compiler is that the static type Ty of the expression assigned to any variable attribute parameter or constant or returned from any function and the static type Td declared for that variable attribute etc must be compatible We say that types Tu and Td are compatible if either one of them is a subtype of the otheriin other words if a value of type Tu might have a type that ts in a Td This is where PYTH differs from Java which requires that Tu be a subtype of Td For example x List x has static type List y x y has by default static type All so this is OK x y This is also OK because y MIGHT contain a List x 3 Error Int not a subtype of List nor viceversa 5 Expressions Expressions can be evaluated so as to yield values In the process of these evaluations they may also have various side e ects on program variables and perhaps things external to the program such as the contents of your display In 14 we saw literals the simplest expressions denoting values of type Int Float and Str The Pyth Programming Language v 32 22 51 Operator expressions Table 3 lists the operators and the equivalent calls grouped by decreasing operator precedence The precedence of an operator determines how to implicitly parenthesize certain combinations of operatorsg Because has higher precedence than for example the expression xyz means xyz and not xyz With one exception all operators are left associative that is in cases of ambiguity in an expression involving two operators of equal precedence PYTH usually groups left to right so that x y z is interpreted as x y z The exception is that is xyz is interpreted as xyz As indicated in Table 3 most PYTH operators are actually syntactic sugar for certain standard function calls also given in Table 3 For example the expression xy3 is exactly equivalent to mulnegx powy3 As a result you can extend the de nitions of operators to new classes that you de ne by simply de ning functions in those classes with names like add Unfortunately PYTH shares a common problem with this technique while you can make myFoo3 mean whatever you want where myFoo contains an object of a class you de ne you can t make 3myFoo mean what you want 52 Operations on numbers The types Int and Float correspond to the Java types int and double Table 4 describes the available operators Their operands must be numbers except as noted although violations of this rule will not in general be discovered until the program is executed The results of these operations unless otherwise noted have the same type as the operands If one operand is Int and the other Float the integer operand is rst converted to the nearest corresponding Float value lnteger arithmetic is performed modulo 232 as in Java 5 3 Sequences The built in sequence classesiTuple List String and Xrangeiimplement operations for fetching members of a set or sequence of items by an integer index 0 based These classes all implement the operations summarized in sugared form in Table 5 see Table 3 for the unsugared function call equivalents 54 Tuples Tuples are immutable sequences of zero or more component values Their components can be of any combination of types They are created by expression lists that are either empty and 9Many authors including alas David Beazley author of the Python Essential Reference mischaracterize operator precedence as determining order of evaluation77 saying things like if is evaluated before Jr77 But in the example xyz it is the operands of and that di eriyou add or multiply di erent things in the two di erent groupings In fact the orderof evaluation description is simply wrong in the case of complex expressions For example in xyuvst it is simply not the case that programming languages require st to be evaluated before xyuv The Pyth Programming Language v 32 23 surrounded in parentheses or that contain at least one comma An expression list is a list of zero or more expressions that are each followed by a comma with the possible exception of the last To represent a tuple the list must be surrounded in parentheses if there are zero expressions in it or it appears in some larger expression 23 23 5 5 1 1 1 are expression lists that evaluate to tuples In the last example the trailing comma is nec essary to indicate a value consisting of a oneelement tuple as opposed to the simple integer 1 Expression lists that are part of list displays see 55 below or argument lists of function calls don t count as tuples An expression list consisting of a single expression with no trailing comma simply yields the value of that expression When necessary you can surround a tuple in parentheses to avoid ambiguity f123 Call function f with three integervalued arguments g123 Call function g with one tuplevalued argument 55 Lists Lists are mutable sequences Like tuples their components can be of any types Unlike tuples the values of individual components may be changed and the length of a list object may change A list display creates a new list It has the form optional expression list Because lists are mutable they support various operations to modify either their length or contents as detailed in Table 6 One can assign to individual elements or slices as indicated in 214 L 123 Q L L1 4 Q L 143 L1 O Q L 140 L1z3 11 12 Q L 11112 LO2 42 Q L 4212 L11 1920 Q L 42192012 Again these assignments are equivalent to calls on setitem and setslice 56 Strings Strings are immutable sequences of characters PYTH doesn t actually have a distinct type character lnstead characters are themselves oneelement stringsl Thus The Pyth Programming Language v 32 24 quotabcquot 1 quotabcquot1 0 quotabcquot1 o o 0 quotbquot Table 7 shows the extra operations de ned on strings beyond the general sequence oper ations already given in Table 5 57 Xranges Xranges are immutable sequences of consecutive integers They are created with the xrange functionixrangeij is the sequence of all integers 2 i and lt j so that xrange1 10 is the sequence of integers from 1 to 9 As a result for i in xrange0 N doSomethingi is the PYTHy way of writing fori0iltNi1 doSomethingi 58 Dicts Dicts are dictionariesimutable mappings from values of almost any types to values of any types Their operations look similar to those of sequences with some subtle differences To create a Dict use a dictionary display K1 V1 KV where n 2 O returns a new Dict object whose getitem operation returns the value of W whenever given a key of Ki and causes an error if given a key that is not one of the Ki The assignment setitem method replaces or sets the value returned by getitem For example d110quotaquot20340 print d1 Prints 10 print d a Prints 20 print d0 ERROR d1 quotqquot d0 42 print d1 Prints q print d0 Prints 42 The keys used may be of any type that implements the hash operation which is essen tially the same as Java s hashCode method This operation is de ned for all types but causes an unimplemented error when applied to mutable prede ned objects lists or dictionaries or immutable objects that contain them A for loop over a Dict produces its currently de ned keys For example The Pyth Programming Language v 32 25 myDict 142 quotaquot 3 True 1 7 for x in myDict print x quotmaps toquot myDict x will print 14 maps to 2 a maps to 3 True maps to 1 7 but not necessarily in that order Table 8 lists other operations on Dicts 59 Selection The dot operator indicates selection of a named entity de ned in some class or object If T is the name of a type including a class then Ta refers to the de nition of a in T This declaration of a will either be prede ned an attribute or defed constant in the de nition of T when T is a user de ned class or a de nition inherited by T Otherwise a selection has the form Ea and E is an expression ie something with a value In this case the search for a de nition is essentially the same as that for Ta where T is the static type of E When the de nition found is an instance variable then the selection refers to the instance of that variable in the object referenced by the value of E It may be assigned to or fetched from class AClass Object instanceVar 3 Declares an instance variable x AClass x AClass Create a new instance xinstanceVar 13 print xinstanceVar Prints 13 In this case a is an instance variable it is a runtime error for E to yield the value None If a refers to an instance method the selection is illegal a compiletime error except when used as the target method in a method call When a does not refer to an instance variable the selection behaves like Ta When the selection is then used as the function in a function call eg E a3 there is additional special treatment described in 510 510 Function calls Function calls have the familiar pre x syntax fa1 an for n 2 0 Here 1 must be a function valued expression The grammar and precedence rules 51 imply that f can only be an identi er selection function call as in incrf 3 array index or slice as in g34 or bracketed expression of some kind parenthesized expression display or string literal The requirement that f be a function rules out displays and strings The Pyth Programming Language v 32 26 More speci cally the type of f in fa1 an must be T1 Tn7 gt To and each T must be a subtype of 0 The type of the returned value must be a subtype of To There are two important special cases A When 1 is a simple identi er ie no dots there is no de nition of f in scope n 2 1 and there is an instance method of a1 named 1 then the function that is called is a1 1 So if foo is not otherwise de ned foox becomes x foo x but rewrite rule B below is not subsequently applied B When 1 is a selection of the form Eg E is a value not a type and g is de ned as an instance method see 34 a copy of the value of E is inserted as the rst parameter of 9 That is Ega1 an becomes in effect EgEa1 an where E is evaluated only once This rewrite rule applies at most once so as not to cause an in nite regress It s probably not immediately obvious but these make PYTH instance methods behave a lot like Java s In Java you might write xf y where instance method f is de ned voidf int p f This calls f and passes two parameters the value of y becomes the value of the explicit formal parameter p and the value of x becomes the value of the implicit parameter this In PYTH the implicit parameter is explicit but otherwise the effect is the same the call is the same as for Java and the de nition of f might be def f self p On the other hand rule A above is a simply a convenience that allows us to write lenmyString and have it mean myStringlen O 511 Restrictions on function values A function value is nested if the function declaration that creates it is itself within the body of another function declaration For reasons we ll get into but you are welcome to gure out for yourselves there are certain restrictions on nested function values that can only be enforced at execution time Speci cally nested function values may not be returned from functions nor may they be stored in instance variables class variables global variables not nested in any function declarations tuples lists or dicts Functions de ned at the outer level outside any class or enclosing function declaration and class methods are therefore not subject to this restriction lnstance methods however are subject to another harsher restriction an instance method may be selected from a value only as the function value in a method call 510 For example glob None def f x global globalVar The Pyth Programming Language v 32 27 def g 0 return x1 callIt g OK passed as parameter tmp g OK assigned to local variable tmp g RUNTIME ERROR stored in list glob g RUNTIME ERROR glob is global glob f OK f not nested AClassaVar g RUNTIME ERROR assigned to class variable inst AClass inst AClass O tmp instmeth ERROR selecting a method without calling instaVar g ERROR assigning to instance variable return g RUNTIME ERROR returned class AClass Object aVar None def meth O 512 Comparisons The comparison operatorsilt gt lt gt iare special in that they evaluate their operands in a unique way In PYTH you can write if 0 lt fx lt 10 and it will mean what you expect the value of f x is between 0 and 9 inclusive In other words a sequence of comparisons E1 lt1 E2 lt2 En where the lti are comparison operators is evaluated according to the following algorithm Set LltE1 and 23992 while i g 71 Set R lt E if not L lti R Comparison yields False stop Set LltR and ilti1 Comparison yields True The interesting points here are that 1 evaluation stops when one comparison yields false and 2 each E is evaluated only once The individual comparisons themselves are simply calls to the comparison methods listed in Table 3 and can therefore be de ned for new classes 513 Boolean values and logical operations PYTH has two literal constant values of type Bool True and False with the obvious mean ings Several contexts in PYTHiif and while statements for exampleirequire a truth value77 By de nition the following values are false values The Pyth Programming Language v 32 28 o The Bool value False o The value None 0 The Int value 0 o The Float values 00 and 700 c Any value of type String List Tuple Xrange or Diet for which the value of len is 0 All other prede ned values are true values The prede ned function truth is declared on all types It converts true values to True and false ones to False lts default value is True but you can override it for any class you introduce The logical operators and or and not described in Table 9 are exceptions to the rule in that they do not correspond to functions unlike most PYTH operators Each of them evaluates only enough of its operands to determine its nal value 514 Files The type File supports a few simple operations for reading and writing bytes from and to an external le As described in 213 the print statement has some special syntax for designating an output le as destination Table 10 describes the other available operations on Files 515 Miscellaneous functions The library class sys must be imported to be used import sys It provides the de nitions shown in Table 11 6 Classes PYTH has classes vaguely resembling Java slo The declaration class class name parent class name suite de nes a new class named class name that extends subtypes inherits from the class parent class name both names are simple identi ers The parent class name must be the prede ned type Object or must appear previously in the program text Class de nitions may only appear at the outer level of a programinot inside a suite so not only are there no nested or local classes but you cannot de ne a class conditionally by putting its de nition in an if statement 10Beware however that they di er markedly from those of PYTHON PYTHON S Classes are much more dynamic than PYTH S The Pyth Programming Language v 32 29 All user de ned classes must eventually inherit from the type Object that is the only valid parent types are Object and user de ned class types prede ned types such as List Any and Void are therefore not extendable 61 Instance variables and class variables lnstance variables also known as attributes are declared by being assigned to in the body of a class declaration but not inside a function de nition For example class AObject x f3 If q is an A then qx is defined y x 7 Likewise qy The scope of these declarations is the body of A not including the bodies of any functions de ned by def in A plus all places where they are made visible by selection see 597that is in expressions like Ex where E is a value whose static type is a subtype of A this is just like Java PYTH like PYTHON handles instance variables rather differently from Java When the declaration of A above is executed variables named Ax and Ay get created and initialized by the assignment statements given After this declaration you can create new instances of A by calling A newA A This expression creates a new object of type A containing new instances of all the instance variables de ned in A and all instance variables in A s supertypes just like Java However the initial values of these variables are copied from Ax Ay and similarly from the supertypes This means that the assignments to x and y in the class de nition for A occur only once not as in Java on every instance creation In fact after Ax 42 q A q A0 the value of 1 will have been initialized to 42 In Java terms there are both instance variables named x and y and corresponding static variables named Ax and Ay that supply their initial values Just as elsewhere you can de ne constants including functions in classes using def Static constant variables are de ned by def name E Since it is static you refer to it either as Trigme where T is the enclosing type or a subtype or Lname where z is an instance of T or a subtype If something is de ned as an instance variable or inherited it may not be rede ned with def and viceversa The Pyth Programming Language v 32 30 62 Instance methods and class methods Instance methods are de ned by def name parameters All instance methods must have at least one parameter The convention not required is to name it self as in def clear self The reason for the convention is that ordinarily the rst parameter of an instance method plays the same role as the quantity variously called self Smalltalk or this Java C A slight variation of this introduces static class methods which are allowed to be pa rameterless class def name parameters This may appear only in a class de nition It may be referred to as Tname where T is the name of the enclosing class or subtype of it The special class method init is used to initialize instances it is a class method whether or not declared as class def It is similar to a Java constructor Its parameter list speci es the parameters that must be supplied to allocate a new object That is the allocation expression A12 rst creates a new A call it new copies in the values of its instance variables from the corresponding static variables in A and then calls A linitnew 1 2 ifthere is a de nition of init immediately within A If you don t supply a de nition of init in a particular class PYTH will allow only a parameterless call A If you don t supply an init function in A Home is called That is unlike Java PYTH does not call the parent s constructor automatically the programmer is supposed to do thisn so that we would write A s constructor like this def init self a b Pinit self 63 Inheritance overriding and hiding As in typical object oriented languages classes inherit the members de ned in their super classes In PYTH This means slightly different things in different caseslz 11No that s not safe but it does follow the practice of PYTHON 12Here again be warned that PYTH s rules are signi cantly di erent from PYTHON s The Pyth Programming Language v 32 31 Static variables and constants As described in 61 de nitions such as class AObject myVar 3 creates a static variable named AmyVar from which instance variables in instances of A are copied When a class B inherits from A the name BmyVar becomes a synonym for AmyVar Likewise if we have de ned class AObject def myConst 17 and B extends A then BmyConst is a synonym for AmyConst The class B may not have its own de nition of myConst nor may it assign to myConst Instance variables Every class inherits one instance variable for each static variable it inherits It follows that there is no overriding or hiding of instance variables if a parent class has an instance variable x of type T then its descendants have one instance variable x or type T Other class methods If A de nes a class static method using the syntax class def fx then B f is a synonym for A f in all subtypes ofA that don t rede ne f A class may only hide a class method of a parent class with another class method The special method init is always a static method regardless of whether it is declared with def or class def Instance methods If class A de nes an instance method class AObject def myMethodself x then its subtype may either inherit this method by not rede ning it or they may override it If subtype B of A inherits myMethod and b is an instance of B then bmyMethod3 or myMethodb3 calls A s method Otherwise subtype B may override A s de nition by providing its own def of it The overriding de nition must have the same number of parameters as that of A Its rst parameter must have the same type as the containing class and its other parameters must have the same types as in the parent class lts return type must be a subtype of the return type of the overridden method The overriding class may provide a type declaration for the method as long as it conforms to these restrictions The Pyth Programming Language v 32 32 Illegal hiding When you de ne a name of something other than an instance method in a subtype that was de ned in the parent type you hide the parent s de nition as opposed to overriding it You can always hide things with parameter names and local variables in function bodies In the bodies of classes but outside function bodies hiding is legal only in certain cases 0 You may not hide an instance variable As a result if myVar is an instance variable of class A and B is a subtype of A then B may not contain an assignment to myVar such as would normally create an instance variable Likewise you cannot provide a def of myVar 0 You may not hide one kind of declaration with another eg a class method declaration with an instance method instance variable or constant declaration 64 Example Figure 1 shows a two class hierarchy The class Parent de nes a constant allObj acts which is supposed to be a list of all objects of type Parent or its subtypes and an integer instance variable X It has two instance methods for incrementing x and for working It de nes a class method that applies incr to all Parent objects on its list and a constructor that sets an initial value for x and adds the newly created object to the list of all Parent objects The subtype Child adds an instance variable S inherits the incr method unchanged and overrides the work method The new work method rst calls the overridden method in Parent in Java you would call superwork to do this and then adds its own actions The constructor for Child as its rst action explicitly calls the parent type s constructor insuring that each Child object will be added to the list of all Parent objects 13You might be momentarily puzzled by the fact that we declared allUbjects as a constant list and then go changing it However allUbjects 239s constantia constant pointer to be precise It is the state of the object it constantly points to that changes The Pyth Programming Language V 32 33 Figure 1 A simple Class hierarchy class Parent Object class Child Parent x Int S String X0 Squotquot allUbjects List init Child Int String gt Void def allUbjects 1 def 1nit self x0 s0 Parentinit self x0 init Parent Int gt Void self S so def init self x0 self x x0 def work self Parent allUbjects self Parent work self print quotThe current name is quot strself S incr Parent Int gt Void def incr self incr self x self x incr def work self print quotThe current value is quot strselfx incrAll Int gt Void class def incrAll x for p in Parent allUbjects pincr x The Pyth Programming Language v 32 Table 2 Operations with nontrivial default implementations for all most types Operation str A hash A truthA A 4 B AisB A is not B Meaning A printable String representation of A Analogous to toString in Java The default implementation produces a string that iden ti es the type and identity of the value An Int value suitable for hashing Analogous to hashValue in Java Normally7 the value should be constant over the lifetime of the object7 and consistent with the operation that is7 ob jects that are should have equal hash values The default implementation returns an integer derived from the identity of the object Returns True if A is a true value see 513 and False otherwise where 4 is any ofthe comparison operations 7 lt7 etc7 returns a truth value see 513 indicating order By default7 the and operators are implemented as is and is not All these7 when applied between a pair of values of different type not both numerical7 either cause an error7 or yield the same truth value for all values with the same pair of types By convention7 if you de ne any of these for a class you introduce7 you should maintain this property Identity test7 returning True or False True iff A and B are the same object All objects are identical to themselves7 and differ ent from objects of other types For types Int7 Float7 String7 Bool7 and Void7 the is operator is the same as the operator Otherwise7 objects created by two different operations are not necessarily identical Same as not A is B 34 The Pyth Programming Language V 32 35 Table 3 PYTH expression operators and corresponding function names Horizontal lines separate operators of di erent precedences highest precedence rst Operator Corresponding func Prede ned meaning tions E17 Tuple display 54 or parenthesiza tion E17 List display 55 K1 V17 Dictionary display 58 EID Attribute eld selection E may be an expression or type name 59 EU getitemEI Array indexing 53 EU J getsliceE7 I7 J Array slice 53 fA1 Ak Function call 510 pow Exponentiation7 right associative 52 Unary 7 quot pos7 neg7 Arithmetic unary operations 52 invert 7 7 mul7 div7 mod Multiplication or repetition7 division7 modulo 52 7 7 add7 sub Addition or catenation7 subtraction 52 ltlt7 gtgt lshift7 rshift Arithmetic shifting 52 amp and Bitwise and 52 quot xor Bitwise xor 52 or Bitwise or 52 lt7 lt lt7 le Comparisons special7 see 512 gt7 gt gt7 ge eq7 ne in contains see Note 1 not in X not in Y iffnot X in Y is Identity Table 2 is not X is not Yiffnot X is Y not Logical negation 513 and Logical and special7 see 513 or Logical or special7 see 513 Note 1 The arguments to contains are reversed A in C7 becomes 0 contains A 7 The Pyth Programming Language v 32 Table 4 Operations on numbers part I 36 Operation E E abs E str E intE float E E1E2 E2 E2 E1E2 oE2 E2 Description The identity Negation Absolute value A string containing an integer or oating point numeral depending on the type of E that denotes E Thus str325 is 325 E converted to an integer E may be an Int in which case the operation is the identity a Float in which case it yields the integer resulting from truncating the fraction of E or a string in which case the result is the integer denoted by the string interpreted as a signed decimal integer literal it is an error in that case if string E does not contain a decimal integer literal E converted to a Float E may be a Float in which case the operation is the identity an Int in which case it yields the nearest Float value to the operand or a string in which case the result is the value denoted by the string interpreted as a signed oating point literal it is an error in that case if string E does not contain such a literal The sum of E1 and E2 The difference of E1 and E2 The product of E1 and E2 The quotient of E1 and E2 For two integer operands yields ElE2 WARNING This is different from Java and C which truncate integer divisions For example in PYTH 13 is 1 not 0 Modulus For integer operands the integer r Whose sign is the same as E2 such that 0 g M lt iE2i and k E2 r E1 for some integer k For oating point operands the formula is the same but r is a Float and the equality is up to round off error77 as usual for oating point Operations E1 raised to the E2 power E2 must be an Int it is not converted nor is E1 The type of the result is the same as that of E1 It is an error for E2 to be negative if E1 is an Int or if it is O The Pyth Programming Language V 32 Table 4 Operations on numbers part II 37 Operation Description E1 4 E2 where 4 is one of the comparison Operators has the usual arithmetic mean ing lf E2 is not a number the result is always true or always false de pending only on the dynamic type of E2 E1 amp E2 The bitwise and of the 32 bit representations of Ints E1 and E2 E1 quot E2 The bitwise exclusive or of the 32 bit representations of Ints E1 and E2 E1 E2 The bitwise or of the 32 bit representations of Ints E1 and E2 quot E The bitwise complement of the 32 bit representation of Int E E1 ltlt E2 E1 shifted left by E2 mod 32 bits modulo 232 as usual The operands must be Ints and E2 2 0 E1 gtgt E2 E1 shifted right by E2 mod 32 bits ie the sign bit is replicated E2 times on the left dropping E2 bits on the right The operands must be Ints and E2 2 O The Pyth Programming Language v 32 Table 5 Common operations on sequence Classes Expression lenS S i Sij Si SlSZ SnnS E1 E2 E1 l E2 E1 4 E2 zinS znotinS Description Number of items in collection 2 0 Element indexed by i in collection S lndices must be integers ilenS i lt lenS lfi lt 0 then Si is equivalent to SilenS ie ith from the end A slice consecutive subsequence having the same type as S and containing all elements or S with indices k where 2 g k lt j Herei iifi 2 Oori ilenS ifi lt 0andj minjlenS So if x is the string quotabcquot then x03 and x0100 are both quotabcquot x02 is quotabquot and x23 is quotbequot Same as Si lenS where S is evaluated once Concatenation of S1 and S2 S1 and S2 must have the same type The result is a new sequence with that same type consisting of the elements of S1 followed by those of S2 where n is an integer concatenates maxn0 copies of S into a new sequence of the same type as S True iff E1 and E2 are sequences of the same type and length with corresponding members Same as not E1 E2 where 4 is one of the comparison operators lt gt lt gt is lex icographic comparison when the operands are sequences of the same type That is the ordering is determined by the rst cor responding members that are not equal If they all are equal but one operand is shorter then it compares less than If the operands have different types the result is consistently either true or false depending only on the types of the operands eg either all strings are less than all lists or greater than all lists in such a way that the comparisons are always transitive True iff zS i for some 2 else False Same as not z in S 38 The Pyth Programming Language v 32 39 Table 6 Operations on lists Operation Description LU E Element assignment see 214 Lij E Slice assignment see 214 Li E Same as LilenL7 but L is evaluated only once appendL E Same as L 1 E listS Create a new list from S Same as the value of L after L l for x in S L append x E1 4 E2 where 4 is one of the usual comparison operators See 512 Table 7 Additional operations on Strings Operation Description strS The identity operation isalphaS True iff all characters in string S are letters isdigitS True iff all characters in string S are digits islowerS True iff all characters in string S are lower case isupperS True iff all characters in string S are upper case lowerS The value of S with all upper case characters replaced by lower case characters upperS The value of S with all lower case characters replaced by upper case characters The Pyth Programming Language v 32 40 Table 8 Operations on dictionaries Operation 1 kl lldelitemlld k Description The value associated with key k Causes an error if k is not a key in 1 Remove key k from d dk V Set the value associated with key k to V lend The number of distinct keys in d k in 1 True iffkisakey in d k not in 1 Same as not k in d cleard Remove all keys from 1 get 1 k v If k is in 1 then dk and otherwise 1 Table 9 Logical operators Operator Description True The true value of type Bool False The false value of type Bool truthX For any value X returns True if X is a true value False other wise E1 and E2 Yields the value of E1 if it is a false value and otherwise yields E2 E2 is not evaluated if E1 yields a false value E1 or E2 Yields E1 if E1 yields a true value and otherwise yields E2 E2 is not evaluated if E1 yields a true value not E Yields False if E yields a true value and otherwise True The Pyth Programming Language v 32 Table 10 Operations on Files Operation openS M closeF readF N readlineF write F S Description Creates a new File that reads from or writes to an external le named S a string The second argument M is a string indicat ing the mode and is one of quotrquot result is an input le quotwquot result is an output le and the external le is rst erased or quotaquot re sult is an output le and all output is appended to whatever was there before Closes the File F making further operations on F illegal Where F is an input File and N is an Int reads data from F and returns it as a String If N 2 0 reads at most N bytes fewer if an end of le is encountered rst Otherwise reads and returns the entire le up to the end of le Returns one line from input File F Reads and returns all char acters up to an including the next end of line or the entire rest of the le if there is no next end of line Writes String S to output File F Table 11 The sys library module Operation exit N stdin stdout stderr argv Description Where N is an integer exits the program with status code N 0 means normal termination A variable initially containing a File reading from the standard input A variable initially containing a File that writes to the standard output A variable initially containing a File that writes to the standard error output A list containing the command line options passed to the pro gram Each element is a string Index operator 36 38 operator 36 operator 36 38 operator 36 operator 36 lt operator 27 38 ltlt operator 37 lt operator 27 38 operator 8 operator 27 38 gt operator 27 38 gt operator 27 38 gtgt operator 37 gtgt in print 8 comment 2 7 operator 36 amp operator 37 quot operator 37 quot operator 37 abs 36 quotaddquot 35 and 35 and operator 40 Any type 19 20 append 39 argv 41 array indexing 35 assignment augmented 10 standard 8710 associativity 22 attributes 29 augmented assignment 10 binding 14 B001 type 19 break statement 12 calling functions 25 class declaration 28 class method 17 42 class methods 30 clear 40 close 41 comment 2 comparison operators 27 38 compatible type 21 compiled language 1 constant declaration 17 constructors 30 contains 35 continue statement 12 continued lines 2 contravariance 18 covariance 18 declaration 14 declarative region 14 DEDENT 3 delitem 40 Dewar Karin footnote 3 dict display 35 Dict type 19 dictionaries 24 dicts 24 div 35 end of line 2 eq 35 expression statement 7 False 27 false value 27 File type 19 les 28 oat 36 Float type 19 oating point literals 5 for loop 13 foreign functions 18 function calls 25 function declaration 17 function type notation 19 The Pyth Programming Language v 32 functions restrictions 26 ge 35 get 40 getindex 13 getitem 35 global statement 16 grouping statements 11 gt 35 hash 34 hiding 15 hole in scope 15 horizontal tabs and indenting 3 identi er 4 if statement 11 immutable 18 import statement 14 18 importing foreign functions 18 in operator 27 38 40 lNDENT 3 indenting lines 3 indexed assignment 39 indexing 38 40 inheritance rules 30732 init 30 31 instance method 17 instance methods 30 instance variables 29 int 36 Int type 19 integer literals 4 interpreted language 1 invert 35 is operator 34 isalpha 39 isdigit 39 islower 39 isupper 39 lattice 18 list 39 43 List type 19 literals 476 local variable 15 lower 39 Wlshift 35 lt 35 method declaring 17 mod 35 mul 35 mutable 18 ne 35 neg 35 nested function 26 not operator 40 Object type 19 octothorpe 2 open 41 operator precedence 22 or 35 or operator 40 overriding methods 31 pass statement 7 pos 35 precedenceoperator 22 prede ned types 18 print statement 7 raw string 6 read 41 readline 41 reference 18 reserved words 4 return statement 13 rshift 35 scope 14 scripting languages 1 selection 25 35 sequences 22 setitem 23 setslice 23 The Pyth Programming Language V 32 44 ShadOWing7 15 variable local 15 simple statement 7 Void type 19 20 slice 35 slice assignment 39 While Statement 12 slicing 357 38 Whitespace 2 source code 1 write 41 statement sequence 7 xor 35 static method 17 static scope 14 static type consistency rule 21 static typing 21 stderr 41 stdin 41 stdout 41 str 34 36 39 str method 8 string literals 5 string operators 23 String type 19 sub 35 subtype 18 sugar syntactic 9 suite 11 supertype 18 syntactic sugar 9 sys class 28 sysargv 41 sysstderr 41 sysstdin 41 sysstdout 41 Xrange type 19 tabs and indenting 3 token 1 True 27 true value 27 truth 34 truth function 28 truth values 27 tuple display 35 Tuple type 19 type declaration 20 types prede ned 18 upper 39


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Anthony Lee UC Santa Barbara

"I bought an awesome study guide, which helped me get an A in my Math 34B class this quarter!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.