Controlling blocks - Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

5. Controlling blocks

This chapter demonstrates how to create code to control the flow of your programs.

Branching choices

Counting loops

Looping conditions

Skipping loops

Catching errors

Summary

Branching choices

As in many programming languages the Python if keyword performs a 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”.

In Python, the tested expression must be followed by a : colon, then statements to execute 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

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

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

Indentation of code is very important in Python as it identifies code blocks to the interpreter – other programming languages use bracketing such as { } braces.

image

if.py

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

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

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 then run the program – to see conditional branching in action

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.

Counting loops

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

for each-item in list-name :

statements-to-execute-on-each-iteration
statements-to-execute-on-each-iteration

Because 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.

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.

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 parentheses. 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.

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.

image

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

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.

image

for.py

imageStart a new program by initializing a regular list, a fixed tuple list, and an associative dictionary list

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

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

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

imageNext, add statements to display all list element values

print( ‘Elements: \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 info.items() :

print( key , ‘=’ , value )

imageSave then run the program – to see the items displayed by the loop iterations

image

image

In programming terms, anything that contains multiple items that can be looped over is described as “iterable”.

Looping conditions

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.

In Python programming, the while keyword creates a loop. It is followed by the test expression then a : colon character. Statements to execute when the test succeeds follow below on separate lines, each line indented from the while test line. Importantly, the loop statement block must include a statement that will change the result of the test expression evaluation – otherwise an infinite loop is created.

image

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

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 interactive Python interpreter automatically indents and waits when it expects further code statements from you.

image

while.py

imageStart a new program by initializing a “counter” variable and define an outer loop using the counter variable in its test expression

i = 1

while i < 4 :

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

print( ‘Outer 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 then 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.

Skipping 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.

image

nest.py

imageStart a new program with a statement creating a loop that iterates three times

for i in range( 1, 4 ) :

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 then 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.

image

break.py

imageInsert a break statement at the start of the inner loop to break from that loop – then run the program again

if i == 2 and j == 1 :

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

break

image

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.

imageNow, insert a continue statement at the start of the inner loop block to skip the first iteration of that loop – then run the program once more

if i == 1 and j == 1 :

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

continue

image

image

The break statement halts all three iterations of the inner loop when the outer loop runs it for the second time.

image

continue.py

image

The continue statement skips the first iteration of the inner loop when the outer loop first runs it.

Catching errors

Sections of a program in which it is possible to anticipate errors, such as those handling user input, can typically be enclosed in a try except block to handle “exception errors”. The statements to be executed are grouped in a try : block and exceptions are passed to the ensuing except : block for handling. Optionally, this may be followed by a finally : block containing statements to be executed after exceptions have been handled.

Python recognizes many built-in exceptions such as the NameError which occurs when a variable name is not found, the IndexError which occurs when trying to address a non-existent list index, and the ValueError which occurs when a built-in operation or function receives an inappropriate value.

Each exception returns a descriptive message that can usefully be assigned to a variable with the as keyword. This can then be used to display the nature of the exception when it occurs.

image

try.py

imageStart a new program by initializing a variable with a string value

title = ‘Coding for Beginners In Easy Steps’

imageNext, add a try statement block that attempts to display the variable value – but specifies the name incorrectly

try :

print( titel )

imageNow, add an except statement block to display an error message when a NameError occurs

except NameError as msg :

print( msg )

imageSave then run the program – to see how the error gets handled

image

image

In some programming languages this structure is known as try-catch exception handling.

Multiple exceptions can be handled by specifiying their type as a comma-separated list in parentheses within the except block:

except ( NameError , IndexError ) as msg :

print( msg )

You can also compel the interpreter to report an exception by using the raise keyword to specify the type of exception to be recognized and a custom descriptive message in parentheses.

image

raise.py

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

day = 32

imageNext, add a try statement block that tests the variable value then specifies an exception and custom message

try :

if day > 31 :

raise ValueError( ‘Invalid Day Number’ )

# More statements to execute get added here.

imageNow, add an except statement block to display an error message when a ValueError occurs

except ValueError as msg :

print( ‘The Program found An’ , msg )

imageThen, add a finally statement block to display a message after the exception has been handled succesfully

finally :

print( ‘But Today Is Beautiful Anyway.’ )

imageSave then run the program – to see the raised error get handled

image

image

Statements in the try block are all executed unless or until an exception occurs.

Summary

•The 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

•Python tested expressions must be followed by a : colon character and statement blocks be indented from the test line

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

•Python for in loop statements must be followed by a : colon character and statement blocks be indented from the statement

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

•The enumerate() function can specify the name of a list to display each element index number and its stored value

•The zip() function can display the stored values of the same index number in multiple lists

•A while loop repeats while an initial test expression remains True and ends when that test expression becomes False

•Python while loop statements must be followed by a : colon character and statement blocks be indented from the statement

•The value of a counter variable can be tested in a test expression to control the number of loop iterations

•The break keyword can be used to test an expression for a True value and immediately exit a loop when the test returns False

•The continue keyword can be used to test an expression for a True value and exit a single iteration when the test returns False

•Anticipated runtime exception errors can be handled by enclosing statements in a try except block

•Optionally, a finally statement can be used to specify statements to be executed after exceptions have been handled

•Python try, except, and finally statements must be followed by a : colon and statement blocks be indented from the statement