Python Summary
Python Summary
Print Function: the print() function takes a list of values to print and writes them to the output, e.g.,
print('cat',5,'dog')
print() # blank line cat 5 dog
print('pi is about', 3.14) pi is about 3.14
Optional keyword arguments can be used to replace the defaults: space-character (' ') as a separator, the
new-line-character ('\n') as the ending character, and output file of the console ([Link]). The syntax
with default parameters explicitly shown is:
print(value,...,sep=' ',end='\n', file=[Link])
String Formatting: inside a string we use formatting placeholders (e.g., %8d, %10s, %5.2f), follow the string
with the format operator (%), and a tuple supplying values for corresponding placeholders. For example:
print(“Name: %10s Age: %-7d GPA: %.2f” % (“Bob”, 20, 3.138)) outputs the line:
Name: Bob Age: 20 GPA: 3.14 %10s means left-justify string in 10 spaces, %-7d means
right-justify decimal/int in 7 spaces, and %.2f left-justify
float using the minimum spaces but with 2 decimal places. Another example with a character and exponent:
print("character: %c float with exponent %e" % ('$', 123.456)) outputs the line:
character: $ float with exponent 1.234560e+02
Assignment Statement: the assignment statement creates a variable in memory and sets its value. The syntax is:
<variable identifier> = <constant or expression value>, where identifiers must start with a letter or underscore
('_'), and then can be followed by letters, underscores, or digits.
Assignment Statements and Print Functions Expected Output
a = 123 a is 124
b = a b is 123
a = a + 1
print ('a is', a)
print ('b is', b)
c = 'cat' c is catfish
d = c d is cat
c = c + 'fish' # string concatenation
print('c is', c)
print('d is', d)
e = ['cat', 'dog'] e = ['cat','dog','cow']
f = e f = ['cat','dog','cow']
[Link]('cow')
print('e is',e)
print('f is', f)
NOTE: This last example deals with assigning lists. In e = ['cat', 'dog'] the variable e is assigned a
reference/pointer to the list, so f = e assigns f a reference to the same list. There is only a single list! Thus,
when we append 'cow' to the list using e’s reference, it also printed in f‘s list because it’s the same list.
The first two examples deal with integers and strings which are immutable (i.e., unchangable). New immutable
values are created with new references being assigned. After b = a both variables reference 123. When
a = a + 1 executes, a new integer constant of 124 is created and its reference is assign to variable a. Variable b
still references 123.
Control Statements: the body of control statements are indented and there is NO other "end" ("}") marker
if statements: An if statement allows code to be executed or not based on the result of a comparison. If the
condition evaluates to True, then the statements of the indented body is executed. If the condition is False, then
the body is skipped. The syntax of if statements is:
if <condition>: if <condition>: if <condition>:
statement1 statementT1 statementT1
statement2 statementT2 statementT2
statement3 else: elif <condition2>:
statementF1 statement
statementF2 statement
else:
statementF1
statementF2
Typically, the condition involves comparing “stuff” using relational operators ( <, >, ==, <=, >=, != ).
Complex conditions might involve several comparisons combined using Boolean operators: not, or, and.
For example, we might want to print “Your grade is B.” if the variable score is less than 90, but greater than or
equal to 80.
if score < 90 and score >= 80:
print( “Your grade is B.” )
The precedence for mathematical operators, Boolean operators, and comparisons are given in the table.
Operator(s)
highest ** (exponential)
+, - (unary pos. & neg.)
*, /, % (rem), // (integer div)
+, - (add, sub)
<, >, ==, <=, >=, !=, <>, is, is not
not
and
lowest or
.
= (assignment)
for loop: the for loop iterates once for each item in some sequence type (i.e, list, tuple, string).
for value in [1, 3, 9, 7]: for character in 'house':
print(value) print( character )
The for loop iterates over an iterable data-structure object (list, string, dictionary) or a range object created by
the built-in range function which generate each value one at a time for each iteration of the loop. The syntax
of: range([start,] end, [, step]), where [ ] are used to denote optional parameters. Examples:
range(5) generates the sequence of values: 0, 1, 2, 3, 4
range(2,7) generates the sequence of values: 2, 3, 4, 5, 6
range(10,2,-1) generates the sequence of values: 10, 9, 8, 7, 6, 5, 4, 3
For example: for count in range(1,6):
print( count, end=" " ) 1 2 3 4 5
print("\nDone") Done
An infinite loop is one that would loop forever. (FYI, in a Python shell ctrl-c (^c)
can be used to kill the running program.) Most infinite loops are caused by
programmer error, but sometimes they are intentional. The following “sentinel-controlled” code uses an infinite
loop and a break statement that immediately causes control to exit the loop.
total = 0
counter = 0
while True: # an infinite loop
score = eval(input("Enter a score (or negative value to exit): "))
if score < 0:
break
total += score
counter += 1
print("Average is", total/counter)
Strings: Strings in Python are sequential collections of only characters. Strings are immutable (i.e., cannot be
changed), so new strings are generated by string operations. Operations on strings (or any sequence
collection) include:
Operation Operator Explanation Example Result of
myString = “Hello!!!” Example
aString = “cat”
Access the element specified myString[1] ‘e’
Indexing [ <index> ]
by the index
Slicing [ : ] Extract a part of the string myString[ 1:5 ] ‘ello’
Concatenation + Combine strings together myString + aString ‘Hello!!!cat’
Concatenate a repeated aString * 3 ‘catcatcat’
Repetition *
number of times
Ask whether a substring is in ‘ell’ in myString True
Membership in
a string
How many items are in the len( myString ) 8
Length len(string)
string?
Indexing of strings starts with 0 on the left end, and -1 on the right end:
1111
01234567890123
cheer = ‘GO Panthers!!!’
-4-3-2-1
Omitted indexes in a slice means “from the end.” For example, cheer[:4] generates ‘GO P’.
Omitted indexes in a slice means “from the end.” For example, cheer[-4:] generates ‘s!!!’.
Lists: A Python list is also a sequence collection, but a list can contain items of any type (e.g., character, strings,
integers, floats, other lists, etc. ), and lists are mutable. Lists are represented by comma-separated values
enclosed in square brackets (‘[’, ‘]’). Operations on lists (or any sequence collection, e.g., strings) include:
Operation Operator Explanation Example Result of Example
myList=[5,6,7,8]
ListB=[8,9]
Access the element
Indexing [ <index> ] myList[2] 7
specified by the index
Slicing [ : ] Extract a part of the list myList[ 1:3 ] [6, 7]
Concatenation + Combine lists together myList + ListB [5, 6, 7, 8, 8, 9]
Concatenate a repeated
Repetition * ListB * 3 [8, 9, 8, 9, 8, 9]
number of times
Ask whether an item is
Membership in 3 in myList False
in a list
How many items are in
Length len(list) len( myList ) 4
the list?
Tuples: A tuple is another sequence data type, so the sequence operations of indexing, slicing, concatenation,
repetition, membership (in), and len() work on tuples too. Tuples are very similar to lists, i.e., comma-separated
items enclosed in parentheses. The main difference is that tuples are immutable (cannot be modified).
Create two tuples as:
student1 = (‘Bob’, 123456, ‘Jr’, 3.12)
student2 = ‘Sally’, 654321, ‘Fr’, 0.0
In addition to indexing, “fields” of a tuple can be unpacked using a single assignment statement as:
name, idnum, rank, gpa = student1
(NOTE: This allows multiple values to be returned from a function)
Dictionaries: A dictionary is an unordered set of key-value pairs (written as key:value). Keys must be unique
and immutable (e.g., numerics, strings, tuples of immutable objects). Dictionaries are typically used to lookup
the value corresponding to a specified key. Dictionaries can be written as comma-separated key:value pairs
enclosed in curly braces. For example,
phoneNumbers = {‘fienup’:35918,‘gray’:35917,‘east’:32939,‘drake’:35811,‘schafer’:32187}
Access to individual key:value pairs looks syntactically like a sequence lookup using a key instead of an
index. For example, phoneNumbers[‘east’] returns 32939, and a new key:value pair can be added by
phoneNumbers[‘wallingford’] = 35919. Additional, methods on dictionaries are:
Below is a summary of the important file-system functions from the os and [Link] modules in Python.
os Module File-system Functions
General syntax Description
getcwd( ) Returns the complete path of the current working directory
chdir(path) Changes the current working directory to path
listdir(path) Returns a list of the names in directory named path
mkdir(path) Creates a new directory named path and places it in the current working directory
rmdir(path) Removes the directory named path from the current working directory
remove(path) Removes the file named path from the current working directory
rename(old, new) Renames the file or directory named old to new
NOTE: The initial “current working directory” is the directory where the program is located. Typically, it is
useful to access files relative to the “current working directory” instead of specifying an absolute (complete)
path. You can use the strings:
'.' to specify the current working directory, e.g., currentDirectoryList = [Link]('.')
'..' to specify the parent of current working directory, e.g., [Link]('..') which changes the current
working directory to the parent directory
Terminology:
a formal parameter is the name of the variable used in the function definition. It receives a value when the
function is called. In the function cube, num is the formal parameter. Formal parameters are only known
inside of the function definition. The section of a program where a variable is known is called its scope, so
the scope of a formal parameter (and other local variable defined in the function such as num_squared) is
limited to the function in which it is defined.
an actual parameter/argument is the value used in the function call that is sent to the function. In the call to
function cube, the variable value supplies the actual parameter value of 2.
a global variable is created outside all functions and is known throughout the whole program file, e.g.
value.
It is helpful to understand the “rules of the game” when a function is called. Memory is used to store the current
program and the data associated with it. The memory used to store the data is divided as shown below.
Global memory is used to store the global variables (and constants).
The heap is used to store dynamically allocated objects as the program runs, e.g. lists, strings, ints, objects
The run-time stack is used to store call-frames (or activation records) that get pushed on the stack when a
function is called, and popped off the stack when a function returns.
When a function is called the section of code doing the calling is temporarily suspended, and a new call-frame
gets pushed on top of the stack before execution of the function body. The call-frame contains the following
information about the function being called:
the return address -- the spot in code where the call to the function occurred. This is needed so execution
(control) can return there when the end of the function is reached or a return statement executes.
room to store the formal parameters used by the function. In Python, parameters are passed-by-value which
means that the value of each actual parameter in the function call is assigned to the corresponding formal
parameter in the function definition before the function starts executing. However, the memory location for
actual parameters for strings, lists, dictionaries, tuples, atomic objects contain only references to the heap
room to store the local variables defined in the function (these are probably references to objects in the heap)
When a function returns, execution resumes at the function call (which is specified by the return address). A
function typically sends back a value to the call by specifying an expression after return in the return
statement. In Python if no expression is specified returned, then the special object None is returned.
play's call-frame
print('BEFORE CALL')
print'anInt=',anInt,'aLongInt=',aLongInt) myInt: 10 11
print('aList=',aList,'aString=',aString) myLongInt 123...890 1234...7891
play(anInt, aLongInt, aList, aString)
print('AFTER CALL') (*) Run-time myList:
print('anInt=',anInt,'aLongInt=',aLongInt) Stack
print('aList=',aList,'aString=',aString) myString:
anInt: 10
aLongInt 1234...7890
Global
Data aList:
aString:
NOTEs:
aList passes a copy of its reference to the list as the initial value of the formal parameter myList, so
both refer to the single list. In play when [Link](1)executes, the single list is changed.
Thus, when play terminates, aList still reflect this change.
aString passes a copy of its reference to the string (‘hello’) as the initial value of the formal parameter
myString. Since strings are immutable (cannot be changed) in Python, executing myString +=
‘a’cause a whole new string ‘helloa’ to be recreated in memory with myString referencing it.
aString still refers to the string ‘hello’.
the int objects should actually be stored in the heap like the string objects since int’s are immutable .
"""
File: simple_die.py
Description: This module defines a six-sided Die class.
"""
class Die(object):
"""This class represents a six-sided die."""
def __init__(self):
"""The initial face of the die."""
self._currentRoll = randint(1, 6)
def roll(self):
"""Resets the die's value to a random number
between 1 and 6."""
self._currentRoll = randint(1, 6)
def getRoll(self):
"""Returns the face value of the die."""
return self._currentRoll
def __str__(self):
"""Returns the string representation of the die."""
return str(self._currentRoll)
Consider the following script to test the Die class and its associated output:
die1 = Die()
die2 = Die() >>>
print('die1 =', die1) #calls __str__ die1 = 2
print('die2 =', die2) die2 = 5
print()
print('[Link]() = ', [Link]()) [Link]() = 2
print('[Link]() = ', [Link]()) [Link]() = 5
[Link]() [Link]() = 3
print('[Link]() = ', [Link]()) str(die1): 3
print('str(die1): ' + str(die1)) die1 + die2: 8
print('die1 + die2:', [Link]() + [Link]()) >>>
die1 = AdvancedDie(100)
die2 = AdvancedDie(100)
die3 = AdvancedDie()
die1 = Number of Sides=100 Roll=32
print( 'die1 =', die1 ) #calls __str__ die2 = Number of Sides=100 Roll=76
print( 'die2 =', die2 ) die3 = Number of Sides=6 Roll=5
print( 'die3 =', die3 ) [Link]() = 32
[Link]() = 100
print( '[Link]() = ', [Link]())
print( '[Link]() =', [Link]()) [Link]() = 70
[Link]() [Link]() = 76
print( '[Link]() = ', [Link]()) die1 == die2: False
print( '[Link]() = ', [Link]()) die1 < die2: True
print( 'die1 == die2:', die1==die2) die1 > die2: False
print( 'die1 < die2:', die1<die2) die1 != die2: True
print( 'die1 > die2:', die1>die2) str(die1): Number of Sides=100 Roll=70
print( 'die1 != die2:', die1!=die2) die1 + die2: 146
print( 'str(die1): ' + str(die1)) Help on class AdvancedDie in module
print( 'die1 + die2:', die1 + die2) advanced_die:
Notice that the [Link] script needed to import AdvancedDie, but not the Die class.
class AdvancedDie(Die):
"""Advanced die class that allows for any number of sides"""
def roll(self):
"""Causes a die to roll itself -- overrides Die class roll"""
self._currentRoll = randint(1, self._numSides)
def __str__(self):
"""Returns the string representation of the AdvancedDie."""
return 'Number of Sides='+str(self._numSides)+' Roll='+str(self._currentRoll)
def getSides(self):
"""Returns the number of sides on the die."""
return self._numSides