Prof. Hilfinger CS164 Lecture 51 The Pyth Language Lecture 5.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Semantic Analysis Chapter 6. Two Flavors  Static (done during compile time) –C –Ada  Dynamic (done during run time) –LISP –Smalltalk  Optimization.
Statement-Level Control Structures
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Title An Introduction to Python. What is Python exactly? Python is a modern rapid development language. Code is very clean and easy to read. Emphasizes.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Python Control of Flow.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Python Control Flow statements There are three control flow statements in Python - if, for and while.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Topics Scope Scope and Lifetime Referencing Environments.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
The Java Programming Language
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
If statements while loop for loop
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
RUBY by Ryan Chase.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Information and Computer Sciences University of Hawaii, Manoa
CS-104 Final Exam Review Victor Norman.
CSC 108H: Introduction to Computer Programming
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
CS190/295 Programming in Python for Life Sciences: Lecture 6
Review for Final Exam.
PHP.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
String and Lists Dr. José M. Reyes Álamo.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Statement-Level Control Structures
Python Primer 1: Types and Operators
Review for Final Exam.
Python Review
CISC101 Reminders Assignment 3 due today.
CSC215 Lecture Control Flow.
Corresponds with Chapter 5
Presentation transcript:

Prof. Hilfinger CS164 Lecture 51 The Pyth Language Lecture 5

Prof. Hilfinger CS164 Lecture 52 Administrivia 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 53 Historical Background Pyth comes from Python, a popular “scripting language” Python comes from ABC, a simple and powerful language for teaching & prototyping

Prof. Hilfinger CS164 Lecture 54 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 55 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

Prof. Hilfinger CS164 Lecture 56 Simple Statements I: Pass Pass does nothing: def f (n): pass # Must be statement here

Prof. Hilfinger CS164 Lecture 57 Simple Statements II: Print 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

Prof. Hilfinger CS164 Lecture 58 Printing to a file print >> sys.stderr, “You made an error” Prints to file sys.stderr (the standard error output) Otherwise like ordinary print.

Prof. Hilfinger CS164 Lecture 59 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 ]

Prof. Hilfinger CS164 Lecture 510 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 511 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”

Prof. Hilfinger CS164 Lecture 512 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 513 Indentation and suites III Tabs indent to multiple of 8 spaces Inconsistent indenting is an error: if x < 0: print x print y # Error

Prof. Hilfinger CS164 Lecture 514 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 515 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.”

Prof. Hilfinger CS164 Lecture 516 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 517 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

Prof. Hilfinger CS164 Lecture 518 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 519 Definitions I: Constants The declaration def name = expression evaluates expression and makes name a constant with that value. (This is not like Python)

Prof. Hilfinger CS164 Lecture 520 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 521 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.

Prof. Hilfinger CS164 Lecture 522 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 523 Local variables and scope II: Global 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 …

Prof. Hilfinger CS164 Lecture 524 Types and type declarations Pyth has a lattice of types: All IntList… Object user-defined types Void arrows show subtypes Function types

Prof. Hilfinger CS164 Lecture 525 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)

Prof. Hilfinger CS164 Lecture 526 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 527 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

Prof. Hilfinger CS164 Lecture 528 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 529 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.

Prof. Hilfinger CS164 Lecture 530 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 531 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]

Prof. Hilfinger CS164 Lecture 532 Xranges Xranges are immutable sequences of Ints. Useful in for loops: for i in xrange (0, N): k += i

Prof. Hilfinger CS164 Lecture 533 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]

Prof. Hilfinger CS164 Lecture 534 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 535 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()

Prof. Hilfinger CS164 Lecture 536 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 537 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.

Prof. Hilfinger CS164 Lecture 538 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 539 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.

Prof. Hilfinger CS164 Lecture 540 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.