Python Concepts

adventurescoldΛογισμικό & κατασκευή λογ/κού

7 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

106 εμφανίσεις

Programming for Beginners,Summer 2011
Python Concepts
Python is a member of the very widely used “imperative” program-
ming language group.Programs in an imperative languages consist of
sequences of actions.Actions are instructions like “display this image”,
or “add these two numbers together and store the result here”.In gen-
eral,actions are thing that occur immediately and cannot be undone.
The key concepts common to all imperative languages are:vari-
ables,sequential execution,loops,conditional statements,and defining
composite actions.
Variables
In an imperative language,a variable is a name given to a unit of stor-
age that contains (or “holds”) a value.The contents (or “value”) of the
variable can be changed with an assignment statement.
For example,in the Python statement myFile = pickAFile( ),the
variable myFile is assigned the name of a file picked by the user.Any
previous value stored in myFile is lost.
After the assignment action,the variable myFile can be used wher-
ever the name of the file picked by the user is needed.The variable
retains this value until it is replaced by another assignment.
In an assignment action,the current value of a variable can be used
in computing its new value.For example,the assignment
myFile = os.path.basename( myFile )
replaces the value of myFile with just the last part of the file path.
Sequential execution
Unless otherwise indicated,actions in an imperative language proceed
one after another,in the sequence in which they are written.
For example,in the Python programbelow,a file name is first picked,
then the file is read in as an image,and then the image is displayed on
the screen:
myFile = pickAFile()
myPicture = makePicture( myFile )
show( myPicture )
Loops
A loop repeats one or more statements a number of times.The state-
ments to repeat are written,indented,beneath the loop control.For
example,
Programming For Beginners,Python Concepts 2
for p in getPixels( myPicture ):
originalRed = getRed( p )
setRed( p,originalRed
*
0.5 )
This Python programrepeats two statements —originalRed = getRed( p )
and setRed( p,originalRed
*
0.5 ) — for each pixel in myPicture.This
particular loop also introduces a variable p,which holds the value of
each pixel in turn.
Conditional statements
A conditional statement selects between one sequence of statements
and another,depending on the values currently held in one or more
variables.
For example,a programthat lets the user decide whether to make a
picture less red or less blue could be written as:
decide = requestString( ’Enter BLUE or RED:’ )
if decide == ’BLUE’:
for p in getPixels( myPicture ):
originalBlue = getBlue( p )
setBlue( p,originalBlue
*
0.5 )
else:
for p in getPixels( myPicture ):
originalRed = getRed( p )
setRed( p,originalRed
*
0.5 )
Defining composite actions
Programs often require a similar sequence of actions to be performed in
several contexts.For example,the sequence “pick a file,make a picture
and show the picture” can be treated as a single action by defining it
as follows:
def pickAndShowImage():
myFile = pickAFile()
myPicture = makePicture( myFile )
show( myPicture )
Once a composite action has been defined,it can be invoking like
any other action.
Programming For Beginners,Python Concepts 3
Defining “similar” sequences of actions
pickAndShowImage always invokes an identical sequence of actions.
However,many “similar” sequences of actions can also be defined that
take into account some of the context in which they are invoked.
For example,the action sequence
for p in getPixels( myPicture ):
originalRed = getRed( p )
setRed( p,originalRed
*
0.5 )
is very similar to the sequence
for p in getPixels( myOtherPicture ):
originalRed = getRed( p )
setRed( p,originalRed
*
0.5 )
The two sequences differ only in the picture they modify.The first
sequence operates on the picture stored in myPicture,and the second
operates on myOtherPicture.An definition that captures both of these
sequences can be written:
def reduceRed( picture ):
for p in getPixels( picture ):
originalRed = getRed( p )
setRed( p,originalRed
*
0.5 )
With this definition,the first action sequence is equivalent to invok-
ing reduceRed( myPicture ) and the second action sequence is equiv-
alent to invoking reduceRed( myOtherPicture ).
The reduceRed definition can be further generalised to capture a
still wider range of similar action sequences by including the amount
of red reduction in the context.
def adjustRed( picture,howmuch ):
for p in getPixels( picture ):
originalRed = getRed( p )
setRed( p,originalRed
*
howmuch )
Now,adjustRed( myPicture,0.5 ) can be used as an alternative (or
replacement) for reduceRed( myPicture ).
Syntax
Every programming language has its own rules of syntax,and the rules
are always rigorously enforced.Syntax rules govern how identifier
names can be written,how assignment actions,loops and conditionals
are written,how action sequences are defined,etc.Very careful atten-
tion to detail is required in order to write correctly formed programs.
For example,the rules governing naming of identifiers include:
Programming For Beginners,Python Concepts 4
• a name must start with either a letter
1
or an underscore;
• the initial letter or underscore can (optionally) be followed by any
number of letters,digits,or underscores;
• upper case letters and lower case letters are considered different,
so x and X are distinct variable names;
• the name cannot be any of:and,del,from,not,while,as,elif,
global,or,with,assert,else,if,pass,yield,break,except,import,
print,class,exec,in,raise,continue,finally,is,return,def,for,
lambda,try;
• names that start and end with two underscores are reserved for
special uses,and should be avoided.
Similarly precise rules also apply to how numbers and text strings
are written,how arithmetic expressions are formed,and to condition-
als,loops and definitions.Rather than attempting to memorise all the
details of the rules of syntax,it is usually sufficient to keep a fewtypical
code fragments at hand and adapt the structure to suit your purposes.
Build-in actions
Python comes with a large number of pre-defined actions that you can
use in your programs.The JES application has a menu “JES Func-
tions” that allows you to select one of the common actions and view its
documentation and a code sample.
—John Hamer,13 June 2011
1
¨
A,˚a,¨o,etc.do not count as letters.