Names and Values - Bryn Mawr Computer Science

Download Report

Transcript Names and Values - Bryn Mawr Computer Science

IDLE Hints

To re-load a module after making changes:
Useful Pylab

savefig('filename.pdf')
Elements of Programming
CSMC 120:Visualizing Information
2/12/08
WHAT’S IN A NAME?
Names are useful because...
Functions
 Modules
 Variables  give name to values


Identifiers
◦ Start with letter or underscore (“_”)
◦ Follow with any sequence of letters, digits, or
underscores
◦ No spaces!
A rose by any other name...
rose
rose2
ROSE
Case-sensitive
rOSE
RoSe
R_O_S_e
Rose
Reserve Words

Some identifiers are part of Python
and
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
yield
Naming Values

Variables
◦ Designated using assignment statements
x = 5
speed = 53.1
myFavoriteFood = 'curry'
<VARIABLE> = <EXPRESSION>
Expressions
>>>
>>>
>>>
>>>

Literal
7
5 + 2
3.0 / 1.7 * 25
mean(x)
An expression is a Python command that
returns a result when evaluated
ILLUMINATING THE
BLACK BOX
A peak inside the black box...

So, what exactly is a variable?
f ( x)  x
2
◦ a space saver
◦ a place to store an unknown (address)
◦ can be used many times
>>> x = 4
>>> x = x + 1
5
4
x
Storage Space or Sticky Note?

>>> x = 4
x
4
Hold address of
memory location
where value is
stored
>>> x = x + 1  Pointer
x
4
5
Parameters

Parameters are a type of variable
>>> time = [10, 20, 30, 40]
>>> distance = [5, 17, 28, 35]
>>> plot(time, distance)
[10, 20, 30, 40]
x
time
[5, 17, 28, 35]
distance
y
Scope

Region of the program in which a name
has meaning
>>> def plus(x, y):
x = x + y
print x
>>> x = 5
>>> x
plus(x,
= plus(x,
2) 2)
7
>>> print x
5
7
VALUES
Types
Computers are “number crunchers”
 A piece of information stored and manipulated
by computer is a datum
 Different types of data are stored and
manipulated in different ways

◦ e.g., 2, 3, 4  whole numbers (integers)
◦ e.g., 2.7, 3.8, 4.9  real numbers (floats)

A data’s type determines:
◦ operations that can be used
◦ limits on size and storage of the value
◦ use of value
Int: The Integers

Whole Numbers: i.e., no fractional part
◦
◦
◦
◦

1
50
11,234,139,514,510587,180,238,401
-75
Use when:
◦ Representing counts
◦ Value cannot be a fraction
◦ Require efficiency or precision

Finite Range
The Limits of Int

Data stored in binary representation
◦ 11=3
◦ 011=3
◦ 0011=3

Number of bits used depends on
computers
◦
◦
◦
◦

32 bits  232 possible integer values
centered at 0, positive and negative
232/2 = 231
integers from -231 to 231 -1
With 32 bits: 2,147,483,647
24 / 2 = 8
Range = -8 to 7
1000
1111
1110
1101
1100
1011
1010
1001
0000
0001
0010
0011
0100
0101
0110
0111
=
-8
-7
-6
-5
-4
-3
-2
-1
0
1
2
3
4
5
6
7
Long Ints

Not fixed in size
◦ Expands to accommodate value
◦ Limit is amount of memory in computer
>>> x = 4L

Ints that grow too large to be represented with
32 bits are automatically converted to long ints

Less efficient
Floats

Any literal that has a decimal point:
◦
◦
◦
◦

1.1
-1.0
573,487.45871157
1.
Stores an approximation to real numbers
◦ limit to precision
◦ limit to accuracy
Useful Python

type(<VALUE>) or type(<VARIABLE>)
>>> type(100L)
<type 'long int'>
>>> type(2.4)
<type 'float‘>
Playing with Numbers


+, -, *, / are operators
%: mod (remainder)
◦ 6/4=1
◦ 6%4=2

**: exponention
◦ 2**3 = 8


Operations performed on floats  floats
Operations performed on ints  ints
◦ 6.0 / 4.0 = 1.5
◦ 6/4=1
Type Conversion
231 + 1  converts int to long int
 x = 5.0 / 2  mixed type expression

◦ Python adds .0 to 2

Explicit type conversion
◦ e.g., calculating an average of a set of integers:
 average = sum / n
 average = float(sum) / n
 average = float(sum / n)
◦ int(<VALUE>)
◦ long(<VALUE>)
Booleans

Used for logical expressions

2 values:
◦ 1 or 0
◦ True or False

hold(1) hold(True)
Strings

Text

Sequence of characters

Deliminated by single quotes
◦ 'my text'
PYTHON POWER:
CREATING YOUR OWN
TYPES
A Point
(x2,y2)
(x,y)
(x1,y1)
x
x1
y
y1
def color(x, y, c):
def label(x, y, l):
def move(x, y, a, b):
Defined by two pieces of data: x and y
 Methods: color, label, move

A Point
Point
p3
x
p
p
Object
p2 Oriented
Object
y
color(c):
label(l):
Programming
move(a, b):
Defined by two pieces of data: x and y
 Methods: color, label, move

Object Oriented Programming

Traditional Programming
◦ Data are passive
◦ Manipulated and combined via active
operations

Objects are active types that combine data
and operations
◦ know stuff
◦ do stuff
Classes

Our point is an example of a class
◦ a construct used to define objects
◦ abstractions

A value whose type is an object is an
instance of the class that defines the
object
Python Demystified
>>> 5 + 2
7
When an expression is evaluated and not
assigned, Python outputs the result of
the expression to the screen
>>> plot(Year, AnyDrug)
[<matplotlib.lines.2D instance at 0x01A0A788>]
plot(x,y) is an expression
 The result it returns is a pointer to an object

◦ Python has created the defining elements of a figure
and stored it at a specific address in memory
>>> myplot = plot(Year, AnyDrug)
Useful Pylab
>>> myplot = plot(Year, AnyDrug)
>>> setp(myplot, linestyle = '--')
>>> x = xlabel('Year')
>>> setp(x, color = 'r')
Lines.2D
• An object defining a two-dimensional
line plot
Data
◦
◦
◦
◦
◦
◦
◦
Dimensions
Line Style
Marker Style
Values being plotted
Labels
Axes Scales
Background Format
Operations
◦
◦
◦
◦
◦
◦
◦
Sizing
Zooming
Labeling
Coloring
Displaying
Scaling
Copying
Using Classes
To perform an operation on an object, we
send the object a message
 Messages to which the object responds
are its methods
 A method is invoked using dot-notation:

<OBJECT>.<METHOD>(<PARAMETERS>)
>>> p.move(a,b)
Useful Pylab
>>> fig = figure(1) Create an Instance of an Object
>>> fig.set_facecolor('g‘)
Useful Pylab
>>> fig2 = figure(2)
>>> fig2.savefig('fig2.pdf')








figure(<#>): create a figure
.savefig(<FILENAME>)
.set_facecolor(<COLOR>)
.set_edgecolor(<COLOR>)
.set_frameon(<BOOLEAN>)
.set_figheight(<#>)
.set_figwidth(<#>)
.hold(<BOOLEAN>)
Useful Pylab
>>> y = ylabel('fig2.pdf')
>>> y.set(color = 'r')