COMMAND | DESCRIPTION | EXAMPLES |
print DATA | displays the DATA in the window |
|
raw_input(STRING) | displays the STRING on the display and waits for the human (``user'') to type something on the keyboard and press Enter | raw_input("Please type something") |
# COMMENT (DOCUMENTATION) STATEMENT | gives one line of explanation about the program for a human to read | # This Game is Over |
arithmetic expressions using integers, addition, subtraction, multiplication, and division | tells Python to compute the answer of the expression |
|
STRING + STRING | concatenates two strings into one | "abc" + "d" |
A Python PROGRAM is a sequence of COMMANDs, one per line. The COMMANDs are executed one after the other.
A COMMAND can be
VARIABLE = EXPRESSIONEXAMPLES: minutes = hours * 60 and hours = int(raw_input("Type an int: "))
The semantics of an assignment goes in two steps:
print EXPRESSION_COMMASwhere EXPRESSION_COMMAS is a sequence of expressions separated by commas. EXAMPLE: print "minutes are", (hours * 60), "."
The semantics is that
There are many possible forms of EXPRESSION:
To print an integer a fixed number of places, use this trick:
num = . . . import string print string.zfill(num, PLACES)where PLACES is a nonnegative int. For example,
cents = 4 print string.zfill(cents, 3)prints 004 --- leading zeroes are added. (When the number is larger than the number of places, the number prints correctly, anyway.)
A Python program has a meaning (semantics): When a program is started, it is copied into computer storage, along with the Python interpreter and an empty namespace. The Python interpreter reads the program's commands, one by one, and tells the CPU what to do to compute the commands. The program's variables are constructed in the namespace.
The new COMMAND is the CONDIIONAL, which can have these forms of syntax:
if CONDITION : COMMANDs
if CONDITION : COMMANDs1 else : COMMANDs2
if CONDITION1 : COMMANDs1 elif CONDITION2 : COMMANDs2 elif CONDITION3: COMMANDs3 ... else : COMMANDsLAST
A CONDITION is an expression that computes to a boolean (True-False) value. CONDITIONs can be built in these ways:
Boolean variables can be used to simplify the structure of a program that must ask many questions to choose its course of action. The style looks like this:
ok = True # remembers if the computation has proceeded correctly so far ... # compute if BAD_CONDITION : ok = False if ok : # if no BAD_CONDITION so far, proceed: ... # compute if BAD_CONDITION : ok = False else : ... # compute if ok : # if no BAD_CONDITION so far, proceed: ... # computeIf a program must be stopped immediately, use the exit command:
import sys sys.exit()
The built-in Python function, randrange, generates random numbers:
import Random # the built-in function lives in module/file Random ... die_roll = Random.randrange(1,7)This generates a random integer in the range of 1 to 6 (!) and assigns it to die_roll.
while CONDITION : COMMANDsThe semantics goes as follows:
count = INITIAL VALUE while CONDITION ON count : EXECUTE COMMANDs INCREMENT countwhere count is the sentry variable.
processing = True # announces when it's time to stop while processing : READ AN INPUT TRANSACTION if THE INPUT INDICATES THAT THE LOOP SHOULD STOP : processing = False else : PROCESS THE TRANSACTION
There is a variation on the above pattern that uses the break command:
while True : READ AN INPUT TRANSACTION; if THE TRANSACTION INDICATES THAT THE LOOP SHOULD STOP : break else : PROCESS THE TRANSACTIONThe break causes the loop to terminate immediately, without executing any more commands in its body.
assert BOOLEAN_EXPRESSIONwhere BOOLEAN_EXPRESSION is an expression that computes to True or False. The semantics goes
for VARIABLE in SEQUENCE : COMMANDswhere VARIABLE is a variable name and SEQUENCE is an expression that computes to a sequence. (See below.) The semantics of the for-loop goes like this:
We also learned about sequences. At the moment, we know of two forms of them:
A SEQUENCE is either
() or (EXPRESSION,) or (EXPRESSION1, EXPRESSION2, ..., EXPRESSIONn) where n > 1
You can ask if a value, E, is a string or a tuple like this:
if isinstance(E, str) : . . . if isinstance(E, tuple) : . . .For example, isinstance("abc", str) computes to True, as does
x = (2,3,4) if isinstance(x, tuple) : . . .but isinstance(2, str) computes to False. (Note that you can also check, isinstance(E,int) and isinstance(E,bool).)
Here are the operations that can be applied to sequences:
len(SEQUENCE)computes to the integer length of SEQUENCE.
SEQUENCE[EXPRESSION]where EXPRESSION computes to a nonegative integer, m, extracts the element numbered by m in the SEQUENCE.
There are also these general forms of indexing, which can extract multiple elements from a sequence:
SEQUENCE[:EXPRESSION]where EXPRESSION computes to nonnegative integer, n.
SEQUENCE[EXPRESSION:]where EXPRESSION computes to nonnegative integer, m.
SEQUENCE[EXPRESSION1:EXPRESSION2]where EXPRESSION1 computes to nonnegative integer, n and EXPRESSION2 computes to nonnegative integer, m.
SEQUENCE1 + SEQUENCE2builds a new sequence whose elements are exactly the ones of SEQUENCE1 followed by SEQUENCE2.
EXPRESSION in SEQUENCEwhich computes to True when the value named by EXPRESSSION is an element within SEQUENCE. (Otherwise, it computes to False.)
Finally, here are many more useful operations on strings:
Similarly, S1.upper() makes a string whose letters are upper case, e.g., for name = "JanE12", name.upper() builds the string, "JANE12".
Similarly, S1.title() capitalizes the first letter of each ``word'' in S1, case, e.g., for book = "The 4 corners of Earth", book.title() builds , "The 4 Corners Of Earth".
data = raw_input("Please type an integer: ") if data.isdigit() : num = int(data) . . . else : print "error --- nonnumeric input"
We can convert between single letters and integers:
To print an integer a fixed number of places, use this trick:
num = . . . import string print string.zfill(num, PLACES)where PLACES is a nonnegative int. For example,
cents = 4 print string.zfill(cents, 3)prints 004 --- leading zeroes are added. (When the number is larger than the number of places, the number prints correctly, anyway.)
line = "abcdecd" pattern = "cd" print line.find(pattern)prints 2, since "cd" first begins at index 2 in line. We can use find to rewrite the FindChar program in Figure 5 like this:
# FindChar # locates the leftmost occurrence of a character in a string. # assumed inputs: s - the string to be searched # c - the character to be found # guaranteed output: if c is in s, then c's position is printed # if c is not in s, then -1 is printed s = raw_input("Type a string: ") c = raw_input("Type a single char to search for: ") c = c[0] # in case the user typed some extra blanks, extract the first char print s.find(c)All the hard work is done by find!
line = "abcabdabe" new_line = line.replace("ab", "!")assigns the string, "!c!d!e" to new_line.
A list is written with this syntax:
[ ELEMENTS ]where ELEMENTS are zero of more EXPRESSIONs, separated by commas. Each expression can compute to any value at all --- number, boolean, string, tuple, list, etc. The elements in a list are saved in the list's cells which are indexed (numbered) by 0, 1, 2, ....
A list can be assigned to a variable, as usual:
gameboard = [ "", "", "", "", "", "", "", "" ]We can use a shortcut to make a list whose items start with the same value:
gameboard = [ "" ] * 8
Given a list, LIS, we can compute its length (number of cells) like this:
len( LIS )The primary operation on lists is indexing, and we can write this indexing expression:
LIS [ INT_EXPRESSION ]where LIS is a list, and INT_EXPRESSION is an expression that computes to an integer that falls between 0 and len( LIS ) -1. The expression returns the element saved at cell number INT_EXPRESSION.
We update a list's cell with this assignment command:
LIS [ INT_EXPRESSION ] = EXPRESSIONThe assignment destroys the value that was formerly held at cell INT_EXPRESSION and replaces it with the value of EXPRESSION.
Since a list is a SEQUENCE, we can use the for-loop to systematically process a list's elements:
for ITEM in LIS : ... ITEM ...where ITEM is a variable name that stands for each element from list LIS.
We can ask if a value, E, is a list by stating isinstance(E, list).
There is a special operation, range, that constructs a list of numbers: range(NUM) builds the list, [0, 1, 2, ..., NUM-1]. (E.g., range(3) computes [0, 1, 2].) We can use range to print a list's index numbers and contents:
for index in range(len(LIS)) : print index, LIS[index]
Here are two methods that alter lists:
s1 = " this is a sentence." words = s1.split() print wordsprints ['this', 'is', 'a', 'sentence.']
time = "12:35:49" words = time.split(":") print wordsprints ['12', '35', '49'].
Lists can be nested inside lists. Here is how to build an 8-by-8 chessboard, a matrix:
board = [ ] for row in range(8) : board.append([ "" ] * 8)We assign to individual cells of the board with two indexes:
board[5][5] = ("white", "pawn")and we use nested for-loops to print the board:
for row in board : for square in row : print square, "|", print
A dictionary is written with this syntax:
{ KEY_ELEMENT_PAIRS }where KEY_ELEMENT_PAIRS are zero or more KEY : ELEMENTs, separated by commas. Each KEY must be an immutable value (number, boolean, string, or tuple). Each ELEMENT can compute to any value at all --- number, boolean, string, list, dictionary, etc. The elements in a list are saved in a hash table structure.
A dictionary can be assigned to a variable, as usual.
Given a dictionary, DICT, we can find an element by using its key:
DICT [ KEY ]But if KEY is not found in DICT, it is an error, so it is better to ask first if the KEY is present:
if KEY in DICT : ... DICT[KEY] ...
We update a dictionary with this assignment command:
DICT [ KEY ] = EXPRESSIONIf the KEY is new to DICT, then a new key, element pair is added. If the KEY is already in use, the assignment destroys the value that was formerly associated with KEY and replaces it with the value of EXPRESSION.
We can use the for-loop to systematically process a dictionary:
for K in DICT : ... K ... DICT[K] ...where K is a variable name that stands for each key saved in dictionary DICT.
We can ask if a value, E, is a dictionary by stating isinstance(E, dict).
The operation, del DICT[K] deletes key K and its element from DICT. (If K is not in DICT, it is an error.)
Here are two useful methods for dictionaries:
keylist = my_dictionary.keys() keylist.sort() for k in keylist: print k, ":", my_dictionary[k]
def NAME(PARAMETERS) : DOC_STRING COMMANDswhere
return EXPRESSION
A function call (invocation) has the format,
NAME(ARGUMENTS)where
A function can also be called with keyword arguments.
A function, F's documentation string can be printed with the command, print F.__doc__
Functions can be written and testing separately, using interactive testing:
>>> import Test >>> from Test import *
>>> fred(..arguments...)This executes the function, just as if it was called from within a program.
>>> reload(Test) >>> from Test import * >>> fred(..arguments...)
There are three important uses of functions:
A variable defined in MODULE is referenced as MODULE.NAME, and a function defined in MODULE is referenced as MODULE.NAME(ARGUMENTS).
There are two main uses of modules:
The benefit is that each module is reasonably sized and can be read and understood in one sitting.
The benefit is that the data-structure module is self contained and can be readily improved or replaced. In particular, all detailed maintenance of the data structure is contained in this one module and nowhere else. The module can be reused in another program if needed.
FIGURE================================================ # This program makes a copy of one sequential file into another. # Ask the user for the names of the files to read from and to write to: inputfilename = raw_input("Type input file to copy: ") outputfilename = raw_input("Type output file: ") # this can be a name of a # file that does not yet exist # A file must be opened --- this requires a new variable to hold the # address in heap storage of the file's data-structure representation: input = open(inputfilename, "r") # "r" means we will read from inputfilename output = open(outputfilename, "w") # "w" means we will write to outputfilename ## You can read the lines one by one with a while loop: # # line = input.readline() # read the next line of input --- this includes # # the ending \r and \n characters! # # The line is of course a string. # # while line != "" : # When the input is all used up, line == "" # print line # output.write(line) # Write the string to the output file # line = input.readline() # But here is the simplest way to read all the lines one by one: for line in input : print line output.write(line) # when finished, you must close the files: input.close() output.close()
A class looks like a module --- it has code for building a data structure and the functions for maintaining the data structure. The code for building the data structure must be inserted inside a special function, a constructor function, named __init__. There are additional functions, such as the event handling function, handle. The class has this form:
============================ class NAME ( BASE_CLASS ) : def __init__(self, ... ) : """constructs the object (namespace) in heap storage. The address of the new object is assigned to the parameter, self. Parameter self is used to define and save the object's variables in its namespace. """ . . . self.mydata = ... # make a variable, mydata, in the object . . . # the function automatically returns the value of self as its answer. def handle(self, ... ) : """event handling function for the object whose address is self""" . . . self.mydata . . . ====================================When the class is used to construct an object, we write this:
x = NAME( ... )The occurrence of NAME on the right-hand side of the assignment is a disguised call of the __init__ function. Indeed, the Python interpreter reformats the above assignment into a ``module'' call in dot notation:
x = NAME.__init__( getNewAddressInHeapForTheNewObject, ... )Notice that an extra argument is supplied for free --- the address in the heap where the new object will be constructed.
Once the object is constructed, the new address is assigned to variable x. A method within the object is called like this:
x.handle(...)Again, the Python intepreter reformats this call, to look like this:
C.handle(x, ...)and now it is clear that the address held by variable x is assigned to parameter self in handle, correctly connecting the object to its event handling function.
We can ask if an object is an instance of a class like this:
class C : . . . x = C() if isinstance(x, C) : . . .