The Pyth Language. Administrivia

Similar documents
UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Introduction to Python

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

Syntax Errors; Static Semantics

Lecture 16: Static Semantics Overview 1

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

Download Python from Any version will do for this class

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

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

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

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

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

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

Beyond Blocks: Python Session #1

Accelerating Information Technology Innovation

Introduction to Programming Using Java (98-388)

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

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

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

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

JAVA MOCK TEST JAVA MOCK TEST II

Babu Madhav Institute of Information Technology, UTU 2015

C and C++ I. Spring 2014 Carola Wenk

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

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Flow Control. CSC215 Lecture

Script language: Python Data structures

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

Senthil Kumaran S

CSE 431S Type Checking. Washington University Spring 2013

The current topic: Python. Announcements. Python. Python

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

CS Summer 2013

And Parallelism. Parallelism in Prolog. OR Parallelism

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

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

Introduction to Python

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

CSE 341, Autumn 2015, Ruby Introduction Summary

Lecture #23: Conversion and Type Inference

Artificial Intelligence A Primer for the Labs

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Key Differences Between Python and Java

Notebook. March 30, 2019

CS Advanced Unix Tools & Scripting

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Python Basics. Lecture and Lab 5 Day Course. Python Basics

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Advanced Algorithms and Computational Models (module A)

Accelerating Information Technology Innovation

CS1 Lecture 3 Jan. 18, 2019

Programming to Python

CSCI-GA Scripting Languages

Swift. Introducing swift. Thomas Woodfin

PREPARING FOR THE FINAL EXAM

CSCE 110 Programming I

Python a modern scripting PL. Python

Lecture #7: Recursion (and a data structure)

Coral Programming Language Reference Manual

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

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

3. Conditional Execution

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

The story so far. Elements of Programming Languages. Pairs in various languages. Pairs

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

FRAC: Language Reference Manual

DSC 201: Data Analysis & Visualization

CS1 Lecture 3 Jan. 22, 2018

python. a presentation to the Rice University CS Club November 30, 2006 Daniel Sandler

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CSE : Python Programming

CS 231 Data Structures and Algorithms, Fall 2016

Python: common syntax

The Decaf Language. 1 Lexical considerations

5. Semantic Analysis!

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

CS 5142 Scripting Languages

Today: Revisit some objects. Programming Languages. Key data structure: Dictionaries. Using Dictionaries. CSE 130 : Winter 2009

Announcements for this Lecture

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

CS558 Programming Languages

Lecture 19: Functions, Types and Data Structures in Haskell

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

MUTABLE LISTS AND DICTIONARIES 4

Compound Data Types 1

1 Lexical Considerations

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

2.Raspberry PI: Architecture & Hardware Specifications

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Lists, loops and decisions

CS 115 Lecture 4. More Python; testing software. Neil Moore

COMP-520 GoLite Tutorial

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

Transcription:

Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof. Hilfinger CS164 Lecture 5 1 Prof. Hilfinger CS164 Lecture 5 2 Historical Background Pyth comes from Python, a popular scripting language Python comes from ABC, a simple and powerful language for teaching & prototyping Features of Pyth Type-safe language, with both dynamic and static typing Object-oriented features based on exemplars Convenient built-in types for sequences, strings, and mappings (dictionaries) Clean, indentation-based statement grouping Prof. Hilfinger CS164 Lecture 5 3 Prof. Hilfinger CS164 Lecture 5 4 Program structure Program is a sequence of statements Each statement is either One or more simple statements on a line, separated by ; s, ending in newline A compound statement A type declaration (new in Pyth) + newline An import statement + newline Simple Statements I: Pass Pass does nothing: def f (n): pass # Must be statement here Prof. Hilfinger CS164 Lecture 5 5 Prof. Hilfinger CS164 Lecture 5 6 1

Simple Statements II: Print Printing to a file To print values separated by spaces: print x,y =, 3, 4 => x,y = 3 4 To print values without newline at end: print x,y =, # Extra comma does it print 3; print 4 => x,y = 3 4 print >> sys.stderr, You made an error Prints to file sys.stderr (the standard error output) Otherwise like ordinary print. Prof. Hilfinger CS164 Lecture 5 7 Prof. Hilfinger CS164 Lecture 5 8 Simple Statements III: Assignment Simple cases like C++ or Java: x = 3; A[i] = 2; q.r = y + 2; z += 1 But we also have: a, b = 1, 10 # a=1; b = 10 (a,b) = 1, 10 # Same thing x, a[0], y = a3elementlist a, (b, c), d = [ 1, (2,3), 4 ] Compound Statements I: if Simplest form looks familiar (fewer () s): if 0 < x < 20: print OK elif x > 30: print too big ; x = 30 else: print too small But only list of simple statements possible after : with this form Prof. Hilfinger CS164 Lecture 5 9 Prof. Hilfinger CS164 Lecture 5 10 Indentation and suites For more complicated thens or elses, use indentation: if x > 0: y = f(x) if y > 0: print y is, y else: # Matches first if print x is negative Indentation and suites II Instead of { }, Pyth (like Python) uses indentation. General form: Line with indentation N: Statement with indentation N >N More lines indented > N Line with indentation N Each more-indented line adds a left bracket Each less-indented line adds a right bracket for each unbalanced more-indented lines Prof. Hilfinger CS164 Lecture 5 11 Prof. Hilfinger CS164 Lecture 5 12 2

Indentation and suites III Tabs indent to multiple of 8 spaces Inconsistent indenting is an error: if x < 0: print x print y # Error Compound Statements II: While While is almost as in Java, modulo parentheses and suites: while n > 0: s += A[n] n -= 1; break and continue as in Java (but no label) Prof. Hilfinger CS164 Lecture 5 13 Prof. Hilfinger CS164 Lecture 5 14 While with else A new twist: end-of-loop code Executes only if test terminates loop: while i < N: if P(A[i]): break i += 1 else: print Error: didn t find it. Compound Statements III: For For loop is like Java 5 s for (String S: L) Works for any type with getindex operation, including built-in sequences: somelist = [2, 3, 5, 7, 11, 13, 17 ]; for p in somelist: if x % p == 0: break else: print Maybe, x, is prime? Prof. Hilfinger CS164 Lecture 5 15 Prof. Hilfinger CS164 Lecture 5 16 Fancier for statements The for statement performs assignment statements to control variables, so pairs = ( ( boy, girl ), ( fish, bike )) for left, right in pairs: print left, is to, right, as => boy is to girl as fish is to bike as Importing In Pyth (not Python), importing is just textual inclusion: import foo Looks for file named foo.py in any directory in search path (see project 1). Importing same name twice has no effect the second time Only allowed at outer level of program. Prof. Hilfinger CS164 Lecture 5 17 Prof. Hilfinger CS164 Lecture 5 18 3

Definitions I: Constants The declaration def name = expression evaluates expression and makes name a constant with that value. (This is not like Python) Definitions II: Constant functions To create a new function (or method) value: def gcd (x, y): if x == y: return x elif x > y: return gcd (x % y, y) else: return gcd (y, x) Functions always return value, but it is the value None by default. Prof. Hilfinger CS164 Lecture 5 19 Prof. Hilfinger CS164 Lecture 5 20 Foreign functions To define a Pyth function with a C function: def newdir (name): import mkdir We ll make extensive use of this to implement all the built-in methods of Pyth. Local variables and scope I Local variable is defined by assigning to it: outer = 2 # outer defined everywhere def f (q): # q defined in body of f x = 2 # x defined in body of f def g (): x = 6 # NEW x, local to g print x, y # will print 6 3 y = 3; g () print outer, x # will print 2 2 Prof. Hilfinger CS164 Lecture 5 21 Prof. Hilfinger CS164 Lecture 5 22 Local variables and scope II: Global Types and type declarations Can assign to outer-level variables in function by declaring them global: errs = 0 # process can change this def process (x): global errs if x < 0: errs += 1; return Pyth has a lattice of types: All Int List Object user-defined types arrows show subtypes Function types Prof. Hilfinger CS164 Lecture 5 23 Void Prof. Hilfinger CS164 Lecture 5 24 4

Types Types all have names: Any Int, Float, Bool, String, Tuple, Xrange, List, Dict, File, Object Types introduced by user with class Function types: (Int, Int) -> Any Void (the type of None) Dynamic and Static Types Every value has a type; types checked at runtime (at latest) for legal operations Every variable has a static type, constraining types of values it may contain (like Java, C, C++, etc.) The type of variable s value is its dynamic type (always a subtype of static type). All of this is just like Java Prof. Hilfinger CS164 Lecture 5 25 Prof. Hilfinger CS164 Lecture 5 26 Declaring Types By default, static type of variable, parameter, named constant is Any. def ed functions by default have type (Any,,Any) -> Any Can declare static type of any of these with: x : Int func : (Int, Int) -> Bool Last one also gives parameters types Pre-Defined Types I: Simple Stuff Ints, Floats are as in Java Constant None is like null in Java Bool is like boolean in Java (constants True, False) String pretty much as in Java But no char type: one-character strings double as characters Prof. Hilfinger CS164 Lecture 5 27 Prof. Hilfinger CS164 Lecture 5 28 Pre-Defined Types II: Sequences Strings, Tuples, Lists, and Xranges are all sequence types. That is, one can write x[i] to get i th character; negative indices count from right. x[-1] is last item. + is concatenation Can slice sequences: x[1: 3] contains x[1], x[2] x[2:] contains everything from 2 on. Tuples Tuples are immutable: can t modify elements Created with expression lists (in () s if needed): (2, a string, True, None, (1,2)) () # Empty (2,) # One element Prof. Hilfinger CS164 Lecture 5 29 Prof. Hilfinger CS164 Lecture 5 30 5

Lists Lists are mutable sequences. Create with list display: [ ] # Empty [ 1, 2, a string ] Change with assignments: L = [ ] ; L += [1]; L += [3] # Now L=[1,3] L[1] = 5; L[0: 1] = [] # L now [5] L[1:] = [9, 11, 13] # L now [5, 9, 11, 13] Xranges Xranges are immutable sequences of Ints. Useful in for loops: for i in xrange (0, N): k += i Prof. Hilfinger CS164 Lecture 5 31 Prof. Hilfinger CS164 Lecture 5 32 Dicts A Dict is a mutable mapping (like Java Map). Convenient syntax: defns = { apple : fruit, car : machine } defns[ cow ] = animal if cow in defns: print defns[ cow ] for key in defns: print key, ->, defns[key] User-defined Classes Pyth supports only single inheritance, no interfaces. To declare a class: class Thing (ParentType): instancevar = 3 def instancemethod (self, dir): class def staticmethod (): def init (self,x): #Constructor Prof. Hilfinger CS164 Lecture 5 33 Prof. Hilfinger CS164 Lecture 5 34 Using A Class Syntax for creating a Thing: Thing (3) creates a Thing and calls constructor ( init ) with new Thing and 3. Access to instance variables, methods, and class methods as in Java: x.instancevar, x.instancemethod( n ), Thing.staticMethod(), x.staticmethod() Instance Methods I The this parameter is explicit in Pyth (and called self by convention): class Cls (Object): var = 0 def Meth (self, x): self.var += x Usual method-calling syntax works by special dispensation: x.meth (3) ==> (x.meth) (x, 3) Prof. Hilfinger CS164 Lecture 5 35 Prof. Hilfinger CS164 Lecture 5 36 6

Instance Methods II: Alternate Syntax If a name f is not otherwise defined, then f(x, ) is transformed into (x.f) (x, ) This strange convention is peculiar to Pyth and due entirely to your instructor s irritation with object-oriented syntax. Initialization and Exemplars I The class definition class Child (Parent): var = 3 def f(self, x): creates a special exemplar instance of Child. Can refer to var in exemplar as Child.var Prof. Hilfinger CS164 Lecture 5 37 Prof. Hilfinger CS164 Lecture 5 38 Initialization and Exemplars II When you create a new Child, its value of var is initialized from Child.var As a result, x1 = Child () Child.var = 42 x2 = Child () print x1.var, x2.var prints 3 42. Operators Most Pyth expression operators are actually just shorthand for function calls. For example: x + y is same as add (x,y) x[i] is same as getitem (x,i) As a result, you can define these operators on your own classes. Prof. Hilfinger CS164 Lecture 5 39 Prof. Hilfinger CS164 Lecture 5 40 7