Making statements - Python in easy steps (2014)

Python in easy steps (2014)

3

Making statements

This chapter demonstrates how statements can evaluate expressions to determine the direction in which a Python program proceeds.

Writing lists

Manipulating lists

Restricting lists

Associating list elements

Branching with if

Looping while true

Looping over items

Breaking out of loops

Summary

Writing lists

In Python programming, a variable must be assigned an initial value (initialized) in the statement that declares it in a program, otherwise the interpreter will report a “not defined” error.

Multiple variables can be initialized with a common value in a single statement using a sequence of = assignments. For example, to simultaneously assign a common value to three variables:

a = b = c = 10

Alternatively, multiple variables can be initialized with differing values in a single statement using comma separators. For example, to simultaneously assign different values to three variables:

a , b , c = 1 , 2 , 3

Unlike regular variables, which can only store a single item of data, a Python “list” is a variable that can store multiple items of data. The data is stored sequentially in list “elements” that are index numbered starting at zero. So the first value is stored in element zero, the second value is stored in element one, and so on.

A list is created much like any other variable but is initialized by assigning values as a comma-separated list between square brackets. For example, creating a list named “nums” like this:

nums = [ 0 , 1 , 2 , 3 , 4 , 5 ]

An individual list element can be referenced using the list name followed by square brackets containing that element’s index number. This means that nums[1] references the second element in the example above - not the first element, as element numbering starts at zero.

image

Lists can have more than one index - to represent multiple dimensions, rather than the single dimension of a regular list. Multi-dimensional lists of three indices and more are uncommon but two-dimensional lists are useful to store grid-based information such as X,Y coordinates.

A list of string values can even be considered to be a multi-dimensional list as each string is itself a list of characters. So each character can be referenced by its index number within its particular string.

imageStart a new Python script by initializing a list of three elements containing string values

quarter = [ ‘January’ , ‘February’ , ‘March’ ]

image

list.py

imageNext, add statements to individually display the value contained in each list element

print( ‘First Month :’ , quarter[0] )

print( ‘Second Month :’ , quarter[1] )

print( ‘Third Month :’ , quarter[2] )

imageAdd a statement to create a multi-dimensional list of two elements, which themselves are lists that each have three elements containing integer values

coords = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ]

imageNow, add statements to display the values contained in two specific inner list elements

print( ‘\nTop Left 0,0 :’ , coords[0][0] )

print( ‘Bottom Right 1,2 :’ , coords[1][2] )

imageFinally, add a statement to display just one character of a string value

print( ‘\nSecond Month First Letter :’ , quarter[1][0] )

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the list element values get displayed

image

image

String indices may also be negative numbers - to start counting from the right where -1 references the last letter.

image

Loop structures, which are introduced later in this chapter, are often used to iterate through list elements.

Manipulating lists

List variables, which can contain multiple items of data, are widely used in Python programming and have a number of “methods” that can be “dot-suffixed” to the list name for manipulation:

List Method:

Description:

list.append(x)

Adds item x to the end of the list

list.extend(L)

Adds all items in list L to the end of the list

list.insert(i,x)

Inserts item x at index position i

list.remove(x)

Removes first item x from the list

list.pop(i)

Removes item at index position i and returns it

list.index(x)

Returns the index position in the list of first item x

list.count(x)

Returns the number of times x appears in the list

list.sort()

Sort all list items, in place

list.reverse()

Reverse all list items, in place

image

For lists that contain both numerical and string values the sort() method returns the list elements sorted first numerically then alphabetically - for example as 1,2,3,A,B,C.

Python also has a useful len(L) function that returns the length of the list L as the total number of elements it contains. Like the index() and count() methods, the returned value is numeric so cannot be directly concatenated to a text string for output.

String representation of numeric values can, however, be produced by Python’s str(n) function for concatenation to other strings, which returns a string version of the numeric n value. Similarly, a string representation of an entire list can be returned by the str(L) function for concatenation to other strings. In both cases, remember that the original version remains unchanged as the returned versions are merely copies of the original version.

Individual list elements can be deleted by specifying their index number to the Python del(i) function. This can remove a single element at a specified i index position, or a “slice” of elements can be removed using slice notation i1:i2 to specify the index number of the first and last element. In this case i1 is the index number of the first element to be removed and all elements up to, but not including, the element at the i2 index number will be removed.

image

Python also has an int(s) function that returns a numeric version of the string s value.

imageStart a new Python script by initializing two lists of three elements each containing string values

basket = [ ‘Apple’ , ‘Bun’ , ‘Cola’ ]

crate = [ ‘Egg’ , ‘Fig’ , ‘Grape’ ]

image

pop.py

imageNext, add statements to display the contents of the first list’s elements and its length

print( ‘Basket List:’ , basket )

print( ‘Basket Elements:’ , len( basket ) )

imageNow, add statements to add an element and display all list elements, then remove the final element and display all list elements once more

basket.append( ‘Damson’ )

print( ‘Appended:’ , basket )

print( ‘Last Item Removed:’ , basket.pop() )

print( ‘Basket List:’ , basket )

imageFinally, add statements to add all elements of the second list to the first list and display all the first list elements, then remove elements and display the first list again

basket.extend( crate )

print( ‘Extended:’ , basket )

del basket[1]

print( ‘Item Removed:‘ , basket )

del basket[1:3]

print( ‘Slice Removed:’ , basket )

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the lists get manipulated

image

image

The last index number in the slice denotes at what point to stop removing elements but the element at that position does not get removed.

Restricting lists

Tuple

The values in a regular list can be changed as the program proceeds (they are “mutable”) but a list can be created with fixed “immutable” values that cannot be changed by the program. A restrictive immutable Python list is known as a “tuple” and is created by assigning values as a comma-separated list between parentheses in a process known as “tuple packing”:

colors-tuple = ( ‘Red’ , ‘Green’ , ‘Red’ , ‘Blue’, ‘Red’ )

image

Like index numbering with lists, the items in a tuple sequence are numbered from zero.

An individual tuple element can be referenced using the tuple name followed by square brackets containing that element’s index number. Usefully, all values stored inside a tuple can be assigned to individual variables in a process known as “sequence unpacking”:

a , b , c , d , e = colors-tuple

image

There must be the same number of variables as items to unpack a tuple.

Set

The values in a regular list can be repeated in its elements, as in the tuple above, but a list of unique values can be created where duplication is not allowed. A restrictive Python list of unique values is known as a “set” and is created by assigning values as a comma-separated list between curly brackets (braces):

phonetic-set = { ‘Alpha’ , ‘Bravo’ , ‘Charlie’ }

Individual set elements cannot be referenced using the set name followed by square brackets containing an index number, but instead sets have methods that can be dot-suffixed to the set name for manipulation and comparison:

Set Method:

Description:

set.add(x)

Adds item x to the set

set.update(x,y,z)

Adds multiple items to the set

set.copy()

Returns a copy of the set

set.pop()

Removes one random item from the set

set.discard( i )

Removes item at position i from the set

set1.intersection(set2)

Returns items that appear in both sets

set1.difference(set2)

Returns items in set1 but not in set2

image

More set methods can be found in the Python documentation.

The Python type() function can be used to ascertain these lists’ data structure class and the Python built-in membership operator in can be used to find values in a set.

imageStart a new Python script by initializing a tuple then display its contents, length, and type

zoo = ( ‘Kangaroo’ , ‘Leopard’ , ‘Moose’ )

print( ‘Tuple:’ , zoo , ‘\tLength:’ , len( zoo ) )

print( type( zoo ) )

image

set.py

imageNext, initialize a set and add another element, then display its contents, length, and type

bag = { ‘Red’ , ‘Green’ , ‘Blue’ }

bag.add( ‘Yellow’ )

print( ‘\nSet:’ , bag , ‘\tLength’ , len( bag ) )

print( type( bag ) )

imageNow, add statements to seek two values in the set

print( ‘\nIs Green In bag Set?:’ , ‘Green’ in bag )

print( ‘Is Orange In bag Set?:’ , ‘Orange’ in bag )

imageFinally, initialize a second set and display its contents, length, and all common values found in both sets

box = { ‘Red’ , ’Purple’ , ‘Yellow’ }

print( ‘\nSet:’ , box , ‘\t\tLength’ , len( box ) )

print( ‘Common To Both Sets:’ , bag.intersection( box ) )

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the tuple and set values

image

image

A set may also be created by specifying the brace-enclosed list within the parentheses of a set() constructor and an immutable set can be created using a frozenset() constructor.

Associating list elements

In Python programming a “dictionary” is a data container that can store multiple items of data as a list of key:value pairs. Unlike regular list container values, which are referenced by their index number, values stored in dictionaries are referenced by their associated key. The key must be unique within that dictionary and is typically a string name although numbers may be used.

image

In other programming languages a list is often called an “array” and a dictionary is often called an “associative array”.

Creating a dictionary is simply a matter of assigning the key:value pairs as a comma-separated list between curly brackets (braces) to a name of your choice. Strings must be enclosed within quotes, as usual, and a : colon character must come between the key and its associated value.

A key:value pair can be deleted from a dictionary by specifying the dictionary name and the pair’s key to the del keyword. Conversely, a key:value pair can be added to a dictionary by assigning a value to the dictionary’s name and a new key.

Python dictionaries have a keys() method that can be dot-suffixed to the dictionary name to return a list, in random order, of all the keys in that dictionary. If you prefer the keys to be sorted into alphanumeric order, simply enclose the statement within the parentheses of the Python sorted()function.

A dictionary can be searched to see if it contains a particular key with the Python in operator, using the syntax key in dictionary. The search will return a Boolean True value when the key is found in the specified dictionary, otherwise it will return False.

image

Data is frequently associated as key:value pairs - for example, when you submit a web form a text value typed into an input field is typically associated with that text field’s name as its key.

Dictionaries are the final type of data container available in Python programming. In summary, the various types are:

Variable - stores a single value

List - stores multiple values in an ordered index

Tuple - stores multiple fixed values in a sequence

Set - stores multiple unique values in an unordered collection

Dictionary - stores multiple unordered key:value pairs

imageStart a new Python script by initializing a dictionary then display its key:value contents

dict = { ‘name’ : ‘Bob’ , ‘ref’ : ‘Python’ , ‘sys’ : ‘Win’ }

print( ‘Dictionary:’ , dict )

image

dict.py

imageNext, display a single value referenced by its key

print( ‘\nReference:’ , dict[ ‘ref’ ] )

imageNow, display all keys within the dictionary

print( ‘\nKeys:’ , dict.keys() )

imageDelete one pair from the dictionary and add a replacement pair then display the new key:value contents

del dict[ ‘name’ ]

dict[ ‘user’ ] = ‘Tom’

print( ‘\nDictionary:’ , dict )

imageFinally, search the dictionary for a specific key and display the result of the search

print( ‘\nIs There A name Key?:’ ,’name’ in dict )

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the dictionary keys and values

image

image

Notice that quotes must be preceded by a backslash escape character within a string - to prevent the string being prematurely terminated.

Branching with if

The Python if keyword performs the basic conditional test that evaluates a given expression for a Boolean value of True or False. This allows a program to proceed in different directions according to the result of the test and is known as “conditional branching”.

The tested expression must be followed by a : colon, then statements to be executed when the test succeeds should follow below on separate lines and each line must be indented from the if test line. The size of the indentation is not important but it must be the same for each line. So the syntax looks like this:

if test-expression :

statements-to-execute-when-test-expression-is-True

statements-to-execute-when-test-expression-is-True

image

Indentation of code is very important in Python as it identifies code blocks to the interpreter - other programming languages use braces.

Optionally, an if test can offer alternative statements to execute when the test fails by appending an else keyword after the statements to be executed when the test succeeds. The else keyword must be followed by a : colon and aligned with the if keyword but its statements must be indented in a likewise manner, so its syntax looks like this:

if test-expression :

statements-to-execute-when-test-expression-is-True

statements-to-execute-when-test-expression-is-True

else :

statements-to-execute-when-test-expression-is-False

statements-to-execute-when-test-expression-is-False

An if test block can be followed by an alternative test using the elif keyword (“else if”) that offers statements to be executed when the alternative test succeeds. This too must be aligned with the if keyword, followed by a : colon, and its statements indented. A final else keyword can then be added to offer alternative statements to execute when the test fails. The syntax for the complete if-elif-else structure looks like this:

if test-expression-1 :

statements-to-execute-when-test-expression-1-is-True

statements-to-execute-when-test-expression-1-is-True

elif test-expression-2 :

statements-to-execute-when-test-expression-2-is-True

statements-to-execute-when-test-expression-2-is-True

else :

statements-to-execute-when-test-expressions-are-False

statements-to-execute-when-test-expressions-are-False

image

The if: elif: else: sequence is the Python equivalent of the switch or case statements found in other languages.

imageStart a new Python script by initializing a variable with user input of an integer value

num = int( input( ‘Please Enter A Number: ‘ ) )

image

if.py

imageNext, test the variable and display an appropriate response

if num > 5 :

print( ‘Number Exceeds 5’ )

elif num < 5 :

print( ‘Number is Less Than 5’ )

else :

print( ‘Number Is 5’ )

imageNow, test the variable again using two expressions and display a response only upon success

if num > 7 and num < 9 :

print( ‘Number is 8’ )

if num == 1 or num == 3 :

print( ‘Number Is 1 or 3’ )

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see conditional branching

image

image

The user input is read as a string value by default so must be cast as an int data type with int() for arithmetical comparison.

image

The and keyword ensures the evaluation is True only when both tests succeed, whereas the or keyword ensures the evaluation is True when either test succeeds.

Looping while true

A loop is a piece of code in a program that automatically repeats. One complete execution of all statements within a loop is called an “iteration” or a “pass”. The length of the loop is controlled by a conditional test made within the loop. While the tested expression is found to be True the loop will continue - until the tested expression is found to be False, at which point the loop ends.

image

Unlike other Python keywords the keywords True and False begin with uppercase letters.

In Python programming, the while keyword creates a loop. It is followed by the test expression then a : colon character. Statements to be executed when the test succeeds should follow below on separate lines and each line must be indented the same space from the while test line. This statement block must include a statement that will at some point change the result of the test expression evaluation - otherwise an infinite loop is created.

Indentation of code blocks must also be observed in Python’s interactive mode - like this example that produces a Fibonacci sequence of numbers from a while loop:

image

Loops can be nested, one within another, to allow complete execution of all iterations of an inner nested loop on each iteration of the outer loop. A “counter” variable can be initialized with a starting value immediately before each loop definition, included in the test expression, and incremented on each iteration until the test fails - at which point the loop ends.

image

The interpreter provides a ... continuation prompt when it expects further statements. Hit Tab to indent each statement then hit Return to continue. Hit Return directly at the continuation prompt to discontinue.

imageStart a new Python script by initializing a “counter” variable and define an outer loop using that variable in its test expression

i = 1

while i < 4 :

image

while.py

imageNext, add indented statements to display the counter’s value and increment its value on each iteration of the loop

print( ‘\nOuter Loop Iteration:’ , i )

i += 1

imageNow, (still indented) initialize a second “counter” variable and define an inner loop using this variable in its test expression

j = 1

while j < 4 :

imageFinally, add further-indented statements to display this counter’s value and increment its value on each iteration

print( ‘\tInner Loop Iteration:‘ , j )

j += 1

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the output displayed on each loop iteration

image

image

The output printed from the inner loop is indented from that of the outer loop by the \t tab character.

image

The += assignment statement i += 1 is simply a shorthand way to say i = i+1 - you can also use *= /= -= shorthand to assign values to variables.

Looping over items

In Python programming the for keyword loops over all items in any list specified to the in keyword. This statement must end with a : colon character and statements to be executed on each iteration of the loop must be indented below, like this:

for each-item in list-name :

statements-to-execute-on-each-iteration

statements-to-execute-on-each-iteration

image

The range() function can generate a sequence that decreases, counting down, as well as those that count upward.

As a string is simply a list of characters, the for in statement can loop over each character. Similarly, a for in statement can loop over each element in a list, each item in a tuple, each member of a set, or each key in a dictionary.

A for in loop iterates over the items of any list or string in the order that they appear in the sequence but you cannot directly specify the number of iterations to make, a halting condition, or the size of iteration step. You can, however, use the Python range() function to iterate over a sequence of numbers by specifying a numeric end value within its parameters. This will generate a sequence that starts at zero and continues up to, but not including, the specified end value. For example, range(5) generates 0,1,2,3,4.

Optionally, you can specify both a start and end value within the parentheses of the range() function, separated by a comma. For example, range(1,5) generates 1,2,3,4. Also, you can specify a start value, end value, and a step value to the range() function as a comma-separated list within its parentheses. For example, range(1,14,4) generates 1,5,9,13.

image

The for loop in Python is unlike that in other languages such as C as it does not allow step size and end to be specified.

You can specify the list’s name within the parentheses of Python’s enumerate() function to display each element’s index number and its associated value.

When looping through multiple lists simultaneously, the element values of the same index number in each list can be displayed together by specifying the list names as a comma-separated list within the parentheses of Python’s zip() function.

When looping through a dictionary you can display each key and its associated value using the dictionary items() method and specifying two comma-separated variable names to the for keyword - one for the key name and the other for its value.

imageStart a new Python script by initializing a list, a tuple, and a dictionary

chars = [ ‘A’ , ‘B’, ‘C’ ]

fruit = ( ‘Apple’ , ‘Banana’ , ‘Cherry’ )

dict = { ‘name’ : ’Mike’ , ‘ref’ : ’Python’ , ‘sys’ : ’Win’ }

image

for.py

imageNext, add statements to display all list element values

print( ‘\nElements:\t’ , end = ‘ ‘ )

for item in chars :

print( item , end = ‘ ‘ )

imageNow, add statements to display all list element values and their relative index number

print( ‘\nEnumerated:\t’ , end = ‘ ‘ )

for item in enumerate( chars ) :

print( item , end = ‘ ‘ )

imageThen, add statements to display all list and tuple elements

print( ‘\nZipped:\t’ , end = ‘ ‘ )

for item in zip( chars , fruit ) :

print( item , end = ‘ ‘ )

imageFinally, add statements to display all dictionary key names and associated element values

print( ‘\nPaired:’ )

for key , value in dict.items() :

print( key , ‘=’ , value )

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the items displayed by the loop iterations

image

image

In Python programming anything that contains mutiple items that can be looped over is described as “iterable”.

Breaking out of loops

The Python break keyword can be used to prematurely terminate a loop when a specified condition is met. The break statement is situated inside the loop statement block and is preceded by a test expression. When the test returns True the loop ends immediately and the program proceeds on to the next task. For example, in a nested inner loop it proceeds to the next iteration of the outer loop.

imageStart a new Python script with a statement creating a loop that iterates three times

for i in range( 1, 4 ) :

image

nest.py

imageNext, add an indented statement creating a “nested” inner loop that also iterates three times

for j in range( 1, 4 ) :

imageNow, add a further-indented statement in the inner loop to display the counter numbers (of both the outer loop and the inner loop) on each iteration of the inner loop

print( ‘Running i=’ , i , ‘ j=’ , j )

imageSave the file in your scripts directory then open a Command Prompt window there and run this program - to see the counter values on each loop iteration

image

image

Compare these nested for loops with the nested while loops example here

imageNow, insert this break statement at the very beginning of the inner loop block, to break out of the inner loop - then save the file and run the program once more

if i == 2 and j == 1 :

print( ‘Breaks inner loop at i=2 j=1’ )

break

image

image

break.py

image

Here, the break statement halts all three iterations of the inner loop when the outer loop tries to run it the second time.

The Python continue keyword can be used to skip a single iteration of a loop when a specified condition is met. The continue statement is situated inside the loop statement block and is preceded by a test expression. When the test returns True that one iteration ends and the program proceeds to the next iteration.

imageInsert this continue statement at the beginning of the inner loop block, to skip the first iteration of the inner loop - then save the file and run the program again

if i == 1 and j == 1 :

print( ‘Continues inner loop at i=1 j=1’ )

continue

image

image

continue.py

image

Here, the continue statement just skips the first iteration of the inner loop when the outer loop tries to run it for the first time.

Summary

In Python, multiple assignments can be used to initialize several variables in a single statement

A Python list is a variable that can store multiple items of data in sequentially-numbered elements that start at zero

Data stored in a list element can be referenced using the list name followed by an index number in [ ] square brackets

The len() function returns the length of a specified list

A Python tuple is an immutable list whose values can be assigned to individual variables by “sequence unpacking”

Data stored in a tuple element can be referenced using the tuple name followed by an index number in [ ] square brackets

A Python set is an ordered collection of unique elements whose values can be compared and manipulated by its methods

Data stored in a set cannot be referenced by index number

A Python dictionary is a list of key:value pairs of data in which each key must be unique

Data stored in a dictionary element can be referenced using the dictionary name followed by its key in [ ] square brackets

The Python if keyword performs a conditional test on an expression for a Boolean value of True or False

Conditional branching provides alternatives to an if test with the else and elif keywords

A while loop repeats until a test expression returns False

A for in loop iterates over each item in a specified list or string

The range() function generates a numerical sequence that can be used to specify the length of a for in loop

The break and continue keywords interrupt loop iterations