Memory in Python [Andersen, Gries, Lee, Marschner, Van Loan, White] - - PowerPoint PPT Presentation

memory in python
SMART_READER_LITE
LIVE PREVIEW

Memory in Python [Andersen, Gries, Lee, Marschner, Van Loan, White] - - PowerPoint PPT Presentation

CS 1110: Introduction to Computing Using Python Lecture 9 Memory in Python [Andersen, Gries, Lee, Marschner, Van Loan, White] Announcements: Assignment 1 A1 is graded. If your A1 is not perfect, your first grade is a 1. This is a


slide-1
SLIDE 1

Memory in Python

Lecture 9

CS 1110:

Introduction to Computing Using Python

[Andersen, Gries, Lee, Marschner, Van Loan, White]

slide-2
SLIDE 2

Announcements: Assignment 1

  • A1 is graded. If your A1 is not perfect, your first grade is a 1.
  • This is a counter for how many times you have submitted.
  • It is not a permanent grade, can resubmit.
  • In order to give students more chances to revise, the March

2nd resubmit deadline is being extended until Sunday, March 5th 11:59pm

  • Review the announcements from the end of Lecture 6 for

policies:

http://www.cs.cornell.edu/courses/cs1110/2017sp/lectures/02-14-17/presentation-06.pdf

  • Read Section 2.3 of A1 carefully to understand how to revise.

2/28/17 Memory in Python 2

slide-3
SLIDE 3
  • Assignment 2 is released
  • Due Tuesday, March 7th at 11:59pm
  • Involves writing on paper
  • Must turn in a legible electronic copy through CMS
  • Lab 5 is released (note there is no Lab 4)
  • Reading: Section 10.1-10.2, 10.4-10.6
  • Prelim conflicts assignment on CMS due

tomorrow because 1st Prelim is March 14th

Announcements

2/28/17 Memory in Python 3

slide-4
SLIDE 4

Storage in Python

  • Global Space
  • What you “start with”
  • Stores global variables
  • Also modules & functions!
  • Lasts until you quit Python
  • Call Frame
  • Variables in function call
  • Deleted when call done
  • Heap Space
  • Where “folders” are stored
  • Have to access indirectly

2/28/17 Memory in Python 4

id2 p id2 1.0

Point3

x incr_x id2 q

Global Space Call Frame

2.0 y 3.0 x

Heap Space

slide-5
SLIDE 5

Memory and the Python Tutor

2/28/17 Memory in Python 5

Global Space Call Frame Heap Space

slide-6
SLIDE 6

Functions and Global Space

  • A function definition…
  • Creates a global variable

(same name as function)

  • Creates a folder for body
  • Puts folder id in variable
  • OPT Link: https://goo.gl/iBfxyo

def to_celsius(x): return 5*(x-32)/9.0

2/28/17 Memory in Python 6

Global Space

id6 to_celsius

Heap Space

id6

Body

function

Body

slide-7
SLIDE 7

Modules and Global Space

import math

2/28/17 Memory in Python 7

Global Space

id5 math

Heap Space

id5

module

  • import…
  • Creates a global variable

(same name as module)

  • Puts contents in a folder
  • variables, functions
  • Puts folder id in variable
  • from dumps contents to

global space

  • OPT: https://goo.gl/4LYvwl

pi 3.141592 e 2.718281 functions

slide-8
SLIDE 8

Modules vs Objects

Module Object

2/28/17 Memory in Python 8

id3 x 5.0 y 2.0 z 3.0 id3 p Point3 id2 id2 math module pi 3.141592 e 2.718281

functions

math.pi math.cos(1) p.x p.distanceTo(q)

slide-9
SLIDE 9

Frames and Helper Functions

  • Functions can call each other!
  • Each call creates a new call frame
  • Function that exists mainly to call other

functions is often called a helper function

2/28/17 Memory in Python 9

slide-10
SLIDE 10

From before: last_name_first

def last_name_first(n): """Returns: copy of <n> but in the form <last-name>, <first-name> Precondition: <n> is in the form <first-name> <last-name> with one or more blanks between the two names. No leading or trailing spaces.""" space_index = n.find(' ') first = n[:space_index] last = n[space_index+1:].strip() return last+', '+first

  • last_name_first('Erik Andersen') gives 'Andersen, Erik'
  • last_name_first('Erik Andersen') gives '

Andersen, Erik'

1 2 3 4

2/28/17 Memory in Python 10

slide-11
SLIDE 11

Frames and Helper Functions

def first_name(s): """Prec: see last_name_first""" end = s.find(' ') return s[0:end] def last_name(s): """Prec: see last_name_first""" end = s.rfind(' ') return s[end+1:]

2/28/17 Memory in Python 11

4 5 6 7 rfind gets the last instance of substring

slide-12
SLIDE 12

Frames and Helper Functions

def first_name(s): """Prec: last_name_first""" end = s.find(' ') return s[0:end] def last_name(s): """Prec: see last_name_first""" end = s.rfind(' ') return s[end+1:]

2/28/17 Memory in Python 12

4 5 6 7 def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + ',' + first 1 2 3

slide-13
SLIDE 13

Frames and Helper Functions

def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + ',' + first def first_name(s): """Prec: see last_name_first""" end = s.find(' ') return s[0:end]

2/28/17 Memory in Python 13

1 2 3 4 5

Call: last_name_first('Erik Andersen'): last_name_first 1 'Erik Andersen'

s

slide-14
SLIDE 14

Frames and Helper Functions

def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + ',' + first def first_name(s): """Prec: see last_name_first""" end = s.find(' ') return s[0:end]

2/28/17 Memory in Python 14

1 2 3

last_name_first 1

s

first_name 'Erik Andersen'

s

4

4 5

'Erik Andersen' Call: last_name_first('Erik Andersen'):

Not done. Do not erase!

slide-15
SLIDE 15

Frames and Helper Functions

def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + ',' + first def first_name(s): """Prec: see last_name_first""" end = s.find(' ') return s[0:end]

2/28/17 Memory in Python 15

1 2 3

last_name_first 1

s

first_name

s end

4 5

4 5

'Erik Andersen' 'Erik Andersen' Call: last_name_first('Erik Andersen'):

slide-16
SLIDE 16

Frames and Helper Functions

def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + ',' + first def first_name(s): """Prec: see last_name_first""" end = s.find(' ') return s[0:end]

2/28/17 Memory in Python 16

last_name_first 1

1 2 3

s

first_name

s end

4 RETURN 'Erik'

4 5

'Erik Andersen' 'Erik Andersen' Call: last_name_first('Erik Andersen'):

slide-17
SLIDE 17

What happens next?

def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + ',' + first

2/28/17 Memory in Python 17

last_name_first 1 1 2 3

s

first_name

s end

4 RETURN 'Erik' 'Erik Andersen' 'Erik Andersen' Call: last_name_first('Erik Andersen'): last_name_first 2

Stuff

A:

ERASE FRAME #2 last_name_first 2

Stuff

B:

first_name

Stuff

C: ERASE FRAME #1

ERASE FRAME #2

slide-18
SLIDE 18

last_name_first 2

s

Frames and Helper Functions

def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + ',' + first def first_name(s): """Prec: see last_name_first""" end = s.find(' ') return s[0:end]

2/28/17 Memory in Python 18

1 2 3

first

'Erik'

4 5

'Erik Andersen' Call: last_name_first('Erik Andersen'):

slide-19
SLIDE 19

Frames and Helper Functions

def last_name_first(s): """Precondition: s in the form <first-name> <last-name>""" first = first_name(s) last = last_name(s) return last + '.' + first def last_name(s): """Prec: see last_name_first""" end = s.rfind(' ') return s[end+1:]

2/28/17 Memory in Python 19

1 2 3

last_name_first 2

s

last_name

s first

6

6 7

'Erik Andersen' 'Erik' 'Erik Andersen' Call: last_name_first('Erik Andersen'):

slide-20
SLIDE 20

The Call Stack

  • Functions are “stacked”
  • Cannot remove one above

w/o removing one below

  • Sometimes draw bottom up

(better fits the metaphor)

  • Python must keep the entire

stack in memory

  • Error if it cannot hold stack

2/28/17 Memory in Python 20

Frame 1 Frame 2 Frame 3 Frame 4 Frame 6 Frame 5 calls calls calls calls

slide-21
SLIDE 21

The Call Stack

  • Functions are “stacked”
  • Cannot remove one above

w/o removing one below

  • Sometimes draw bottom up

(better fits the metaphor)

  • Python must keep the entire

stack in memory

  • Error if it cannot hold stack

2/28/17 Memory in Python 21

Frame 1 Frame 2 Frame 3 Frame 4 calls calls calls

slide-22
SLIDE 22

The Call Stack

  • Functions are “stacked”
  • Cannot remove one above

w/o removing one below

  • Sometimes draw bottom up

(better fits the metaphor)

  • Python must keep the entire

stack in memory

  • Error if it cannot hold stack

2/28/17 Memory in Python 22

Frame 1 Frame 2 Frame 3 Frame 4 Frame 6 calls calls calls calls

slide-23
SLIDE 23

Example

2/28/17 Memory in Python 23

def function_1(x,y): return function_2(x,y) def function_2(x,y): return function_3(x,y) def function_3(x,y): return x+y print function_1(1,0)

calls calls

OPT Link: https://goo.gl/ckBJh9

calls

slide-24
SLIDE 24

Errors and the Call Stack

# error.py def function_1(x,y): return function_2(x,y) def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y print function_1(1,0)

Crashes here (division by 0)

2/28/17 Memory in Python 24

slide-25
SLIDE 25

Errors and the Call Stack

# error.py def function_1(x,y): return function_2(x,y) def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y # crash here print function_1(1,0)

Crashes produce the call stack:

Traceback (most recent call last): File "error.py", line 20, in <module> print function_1(1,0) File "error.py", line 7, in function_1 return function_2(x,y) File "error.py", line 11, in function_2 return function_3(x,y) File "error.py", line 15, in function_3 return x/y Make sure you can see line numbers in Komodo. Preferences  Editor

2/28/17 Memory in Python 25

slide-26
SLIDE 26

Errors and the Call Stack

# error.py def function_1(x,y): return function_2(x,y) def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y # crash here print function_1(1,0)

Crashes produce the call stack:

Traceback (most recent call last): File "error.py", line 20, in <module> print function_1(1,0) File "error.py", line 7, in function_1 return function_2(x,y) File "error.py", line 11, in function_2 return function_3(x,y) File "error.py", line 15, in function_3 return x/y Make sure you can see line numbers in Komodo. Preferences  Editor

Where error occurred (or where was found) Script code. Global space

2/28/17 Memory in Python 26

slide-27
SLIDE 27

assert statement

  • Format: assert <boolean expression>
  • Throws error if <boolean expression> is False
  • assert <boolean expression>, <error message>
  • Same thing but prints <error message>
  • Useful if you want to know what happened

2/28/17 Memory in Python 27

slide-28
SLIDE 28

asserting preconditions

  • Useful purpose of assert: assert preconditions
  • Throws error if precondition violated

2/28/17 Memory in Python 28

def exchange(from_c, to_c, amt) """Returns: amt from exchange Precondition: amt is a number…""" assert type(amt) == float or type(amt) == int …

slide-29
SLIDE 29

Recovering from Errors

  • try-except blocks allow us to recover from errors
  • Executes code beneath try
  • Once an error occurs, jump to except
  • Example:

try: input = raw_input() # get number from user x = float(input) # convert string to float print 'The next number is '+str(x+1) except: print 'Hey! That is not a number!' might have an error executes if error happens

2/28/17 29 Memory in Python

slide-30
SLIDE 30

Comparison

if-else

  • if vs. else depends on

Boolean expression

  • Never executes both branches

try-except

  • Always does try
  • May not finish try if there is

an error

  • then goes to except

2/28/17 Memory in Python 30

slide-31
SLIDE 31

Try-Except is Very Versatile

def isfloat(s): """Returns: True if string s represents a number""" try: x = float(s) return True except: return False

2/28/17 Memory in Python 31

Conversion to a float might fail If attempt succeeds, string s is a float Otherwise, it is not

slide-32
SLIDE 32

Try-Except and the Call Stack

# recover.py def function_1(x,y): try: return function_2(x,y) except: return float('inf') def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y # crash here

  • Error “pops” frames off stack
  • Starts from the stack bottom
  • Continues until it sees that

current line is in a try-block

  • Jumps to except, and then

proceeds as if no error

2/28/17 Memory in Python 32

function_1 function_2 function_3 pops pops line in a try

slide-33
SLIDE 33

Try-Except and the Call Stack

# recover.py def function_1(x,y): try: return function_2(x,y) except: return float('inf') def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y # crash here

  • Error “pops” frames off stack
  • Starts from the stack bottom
  • Continues until it sees that

current line is in a try-block

  • Jumps to except, and then

proceeds as if no error

  • Example:

>>> print function_1(1,0) inf >>>

2/28/17 Memory in Python 33

No traceback! How to return ∞ as a float.

slide-34
SLIDE 34

Tracing Control Flow

def first(x): print 'Starting first.' try: second(x) except: print 'Caught at first’ print 'Ending first’ def second(x): print 'Starting second.' try: third(x) except: print 'Caught at second’ print 'Ending second’ def third(x): print 'Starting third.' assert x < 1 print ’Ending third.'

What is the output of first(2)?

'Starting first.' 'Starting second.' 'Starting third.' 'Caught at second' 'Ending second' 'Ending first'

2/28/17 Memory in Python 34

slide-35
SLIDE 35

Tracing Control Flow

def first(x): print 'Starting first.' try: second(x) except: print 'Caught at first’ print 'Ending first’ def second(x): print 'Starting second.' try: third(x) except: print 'Caught at second’ print 'Ending second’ def third(x): print 'Starting third.' assert x < 1 print ’Ending third.'

What is the output of first(0)?

'Starting first.' 'Starting second.' 'Starting third.' 'Ending third' 'Ending second' 'Ending first'

2/28/17 Memory in Python 35