OBJECTIVES

  • Show how to apply logic in programming languages.
  • Demonstrate good practices when using loops and conditionals.
  • Discuss the important programming styles available.
  • Explain how best to handle state and its effects in your programs.
  • Demonstrate advanced constructs that help to make programs easier to manage.

LOGIC

Chapter 2 introduced the basic ideas of logical thinking. This section shows how to incorporate some of those ideas directly in a programming language using Python as a demonstration.

Recap

Proper use of logical operators is discussed in Chapter 2 , section called ‘Logical Thinking’. Some common mistakes using logical operators are discussed in the same chapter in a section called ‘Gotchas’.

Logical propositions are statements in logic that evaluate to true or false. Individual propositions can be combined into a compound proposition that is true or false overall. In this case, they’re combined using logical operators that correspond (imperfectly) to those in natural language (‘and’, ‘or’, ‘not’, etc.).

Propositions in Python

Python is a programming language, not a logic language. As such, it doesn’t provide a means to write propositions, but it does support something similar in the form of expressions. An expression is a piece of code that you can evaluate to obtain a result. For example, ‘ 1 + 2 ’ is an expression because it evaluates to 3.

‘ x > 42 ’ is also an expression because (depending on the value of x ) it evaluates either to True or False . An expression that evaluates to True or False is the nearest thing to a proposition you’ll find in Python.

images

Expressions typically form parts of Python statements (a statement is a line in a program that performs an action). if x > 42: and my_number = 1 + 2 are both examples of statements containing expressions.

Logical operators in Python

Python provides three logical operators (see Table 8.1 ), which work in much the same way as their counterparts from pure logic. These operators can combine several expressions into a single, complex expression.

Table 8.1 Logical operators in Python

Operator

Python keyword

Python code example

Logical AND

and

on_vacation and is_sunny

Logical OR

or

player_has_row or all_squares_occupied

Logical NOT

not

not (score < 50 or score > 80)

Parentheses can be used in expressions, either to improve readability or to override the usual order of precedence for operators. Python borrows the order of precedence from mathematics intact, although it also adds some additional symbols without equivalents in mathematics (such as the assignment operator). See Appendix A for the order of operations in Python.

BASIC ALGORITHMIC CONSTRUCTS

Chapter 2 introduced algorithms as a fundamental means of creating solutions and explained the basic building blocks of every algorithm. Every programming language gives you ways to use those basic building blocks. This section demonstrates them.

Recap

images

Basic constructs of algorithms were discussed in Chapter 2 , in the subsection, ‘Defining algorithms’.

Let’s recap the basics of algorithms. Despite their enormous applicability, even the most complex of algorithms is essentially made up of the following basic constructs:

  • Sequences: a series of instructions executed (one after the other).
  • Conditionals: a branching point where instructions are executed only if a certain condition is met.
  • Iterations: a sequence that is executed repeatedly so long as a certain condition holds.

Figure 8.1 depicts each construct as a flow chart.

Figure 8.1 Flow charts of the three basic algorithmic constructs

Flowchart: Three flowcharts labelled Sequence, Conditional, and Iteration, illustrating different control structures in programming.

While other more sophisticated constructs exist, all of them boil down to some arrangement of these three constructs.

Sequence

Sequence takes place automatically in Python. Each line is executed one after another.

This program asks you three questions, and then echoes

back your responses in a sentence.# input() is a function in Python that allows the user to# type in some text. That text is assigned to a variable.name = input(‘What is your name?’)

quest = input( ‘What is your quest?’)
colour = input(‘What is your favourite colour?’)

print(‘Your name is’, name, ‘your quest is’, quest, \
‘and your favourite colour is’, colour)

print(response)

A couple of ways you might get caught out:

  • One statement usually occupies one line in a file, but longer instructions can be split over several lines to improve readability. Any line that ends with a backslash ( \ ) character means that the current instruction continues on the next line.
  • Exceptions 53 can cause the expected flow of control to be interrupted in unpredictable ways. Read more about exceptions and how to tame their unpredictability in Chapter 12 .

Conditional

Python has one conditional construct: the if-statement, an example of its simplest form being:

images

images

Notice the indentation of the second instruction. Python uses indentation to denote structure, so blocks of instructions ‘inside’ a particular construct are pushed along a few spaces. To make it even clearer, a statement that opens up a new code block (like an if-statement does) ends with a colon.

You must respect this rule, otherwise your code won’t run correctly.

Complex conditionals

An if-statement can also include many optional parts. First of all, it can include an optional ‘else’ block. The instructions in this section will be executed only if all previous conditions were evaluated as false.

images

An if-statement may include any number of elif blocks ( elif <condition>: ). elif is a short way of saying ‘else if’. At most, one elif is executed and only if all previous conditions were evaluated as false.

The following example demonstrates elif . It calculates a grade based on test scores (80+ gains an A grade, 70–79 a B, 60–69 a C, 50–59 a D, and anything else is an F).

images

images

As soon as one condition in an if–statement is evaluated as true, the code in its corresponding block is executed and all following parts of that if-statement are ignored. In other words, only one part of an if-statement at most will be executed.

Be careful with your conditions. If none of the conditions in an if-statement is true, then none of those corresponding blocks will be executed. Also, if more than one condition can be true simultaneously, you will need to order the parts carefully or you risk executing the wrong block. Keep in mind that conditions are evaluated top to bottom.

The previous example works correctly because conditions are tested in descending order of grade value. But what would happen if the conditions were rearranged like this?

images

A student who scored 56 would be (correctly) awarded a D. However, a student who scored 73 would also be awarded a D, because their score matches the first condition.

images

As noted in Chapter 2 , the behaviour of the ‘if-then’ form differs somewhat from the similarly named concept in pure logic. An if-statement in a Python program instructs the computer to make a decision regarding whether to execute the code inside the following block. That decision depends on how the associated condition is evaluated at that instant.

Conditional expressions

Python also includes a variation on the if-statement called a conditional expression . If the value of something depends on some condition, you might normally write code like this:

images

A more concise way is to use a conditional expression, which has the form: [value if true] if [condition] else [value if false] . The previous example could therefore be rewritten like so:

max = a if a > b else b

Iteration

This construct allows you to execute the same sequence of steps repeatedly. Python provides two constructs for this.

The while loop executes a block of instructions repeatedly for as long as some condition evaluates to true. The value of the condition is only checked at the beginning of each iteration. As soon as the condition evaluates to false, the loop ends and execution jumps immediately to the next line following the end of the while block.

images

images

The built-in function len(x) calculates the length of its parameter x. For example, if x is a list with 3 items in it, len(x) would evaluate to 3.

The for-loop sets up a control variable that manages execution of the loop. Execution iterates over the items in a sequence (the value of each item is assigned to the control variable at the beginning of each pass through the loop). That sequence could, for example, be a list. In the following code sample, the variable word is used as a control variable. At the beginning of each iteration of the loop, it is assigned the next value from the list words from beginning to end.

images

images

The built-in function range (x, y) produces a list of numbers from x to y-1.

or, if you know exactly how many iterations to execute, a range:

images

images

Exercise caution when using ranges. Remember Beizer’s (1990) advice mentioned in Chapter 5 : ‘bugs lurk in corners and congregate at boundaries’. In a Python range, the first number is inclusive and the second is exclusive. Hence, range(1, 5) includes the numbers 1, 2, 3 and 4.

Cutting an iteration short

To prematurely end an iteration and move onto the next, Python provides the continue statement. This can be placed anywhere inside a loop. Upon encountering it, execution will immediately skip the rest of the block, jump to the beginning of the loop and start the next iteration.

Figure 8.2 depicts this as a flow chart.

Figure 8.2 Flow chart of the continue statement

Loop flowchart: A flowchart depicting a loop condition and statements, showing possible continuation or completion paths.

The following program compares each number in a list to see if it is greater than, less than, or equal to a test number. If either of the first two comparisons are successful, all the following comparisons don’t need to be carried out, so the computer can jump immediately back to the beginning of the loop and move onto checking the next number in the list.

numbers = [3, 8, 1, 9, 5]
test_number = 5

for n in numbers:
If test_number > n:

print(‘Greater than’)
continue
if test_number < n:
print(‘Less than’)
continue
if test_number == n:
print(‘Equal to’)

Prematurely exiting a loop altogether

Sometimes it makes sense to stop execution of a loop immediately and move on. For these situations, Python provides the break statement.

Figure 8.3 depicts this as a flow chart.

Figure 8.3 Flow chart of the break statement

Loop flowchart: A flowchart depicting a loop with a break condition leading to termination of the process.

For example, in a number-guessing game, where the computer thinks of a number and the player is allowed several guesses, there’s no need to keep asking the player after they’ve guessed correctly:

images

PROGRAM STATE

images

The fundamental nature of state in algorithms is discussed in the Chapter 2 , subsection ‘Defining algorithms’.

Because a program is executed step by step, you sometimes need to record the results of certain steps for use in later steps. The term ‘state’ describes the current values of all pieces of information kept track of by a program. But because the values of variables can change from moment to moment during a program’s execution, it’s essential to carefully manage the handling of state.

Using variables

The state you deal with in a computer program takes the form of variables. Because a program is executed one statement at a time, the value of variables can vary from moment to moment, so it’s important to be able to track changes in variables.

It can be helpful to think of program variables as you would variables in a mathematical formula. However, because programming languages store variables in computer memory, this raises some important distinctions you must keep in mind.

This first, simple example demonstrating a value changing from one moment to the next highlights one of the differences:

x = 42
print(x) # Prints 42

x = x + 1
print(x) # Prints 43

x = x * 2
print(x) # Prints 86

Writing a mathematical formula like x = x + 1 would be nonsensical. That’s because the formula is stating ‘x is the same as x plus one’ (which cannot be true), whereas the same statement in a Python program is saying ‘compute the value of x plus one, then assign it to x’. This is perfectly fine in a Python program, because of the way it stores variables.

images

Each programming language stores variables in memory in its own way. Whichever language you choose, you must learn its approach to handling variables. Since this book uses Python, we focus on how Python handles variables.

In Python, a variable 54 can be thought of as a label that’s attached to a value. The act of assigning a variable name is like attaching it to a value in memory. Therefore, executing this:

x = 42
name = ‘Arthur’

can be thought of as creating the values 42 and ‘Arthur’ then attaching to them the labels x and name respectively (see Figure 8.4 ).

Figure 8.4 Assigning values

Diagram: Memory representation showing variable X pointing to 42 and name pointing to the string Arthur.

Normally, once a Python creates a value in memory, that value can’t subsequently be changed. However, we’ve already seen examples that show variables can easily be reassigned new values. This is possible because giving a variable a new value is akin to creating the new value in a different place in memory and then moving the existing label to point at it. If we extend the last program like this:

x = 42
name = ‘Arthur’
x = x + 1

then, after execution of the first two lines, the state of the program in memory is represented in Figure 8.4 . The state after execution of the third line is represented in Figure 8.5 .

Figure 8.5 Reassigning values

Diagram: Memory representation showing variable X pointing to 43 and name pointing to Arthur.

In an assignment, the right-hand side of the equals sign can be a value (like 42) or an expression (like x + 1 , in which case, the expression is first evaluated before being assigned). Consider this:

x = 42
y = x

In this example, x is not a value, but simply another variable name (a trivial expression). Therefore, the value of x is first looked up and that is assigned to y .

Mutability

In an ideal world, variables in a programming language would always work in the same way. However, that’s usually not the case. Programming languages often deal with larger and more complex data differently from simple data due to efficiency concerns, and Python is no exception. The method described in the previous section only applies to simple data (like numbers, Boolean values and strings). This all has effects on how your program behaves, so it’s important to know.

Consider what would happen if you execute this program:

x = 42
y = x
x = 99
print(y)

It should be apparent by now that the statement x = 99 doesn’t affect the value of y and so the program will print ‘42’. That’s because when x is reassigned, a new space in memory is created for the value 99 and the x label is moved to point to that new space ( y remains pointing to 42). You probably think that’s desirable behaviour – you don’t want changes made to one variable inadvertently affecting another. Data that behaves like this (i.e. data that cannot be changed in-place, meaning that assignment means creating new values) is referred to as immutable .

Unlike numbers, lists are an example of data that can get large and complex. As a result, managing their state can become complicated. For example, did you know that there are (at least) two ways to add a new item to a list (see Figure 8.6 )?

names = [‘Tom’, ‘Dick’ ]

# Method 1
names = names + [‘Harry’]

# Method 2
names.append(‘Harry’)

There is a reason for this.

  • The approach in method 1 behaves just like the earlier examples that assigned numbers. When it’s executed, a new space in memory is created. The computer takes a copy of the existing two names (Tom and Dick), puts them together with Harry and puts the resulting new list into that memory space.
  • Method 2 behaves differently. It doesn’t create a new memory space. Instead, it changes the list in-place and leaves the names label pointing to the existing memory space. This is because lists are mutable . Mutable items of data can be changed in-place.

Method 2 works more efficiently, especially on lists that are very large, because the computer doesn’t need to go to the trouble of copying the existing list items into a new space in memory. However, efficiency isn’t the only consequence to be mindful of.

images

Using immutable objects can come at an efficiency cost. ‘Updating’ an immutable object is done by creating a whole new object, and this usually takes more resources. This may or may not be a problem. For example, for a video game, where lots of objects are updated continually, this extra cost might visibly slow the game down.

Consider this program:

notes_1 = [‘Do’, ‘Re’, ‘Me’]
notes_2 = notes_1
notes_1.append(‘Fa’)
print(notes_2)

When this program executes, we find it prints out “[‘Do’, ‘Re’, ‘Me’, ‘Fa’]” ! Why? Because, assigning one mutable variable ( notes_1 ) to another ( notes_2 ) doesn’t create a new space in memory. Instead, it makes the label of the assignee point at the existing memory space of the source variable. After line 2 is executed, notes_1 and notes_2 both refer to the same memory space (a list containing ‘Do’, ‘Ra’ and ‘Me’). Altering notes_1 in-place also alters notes_2 as a side effect (see Figure 8.7 ).

Figure 8.6 Executing two different ways of adding to a list

Diagram: A sequence showing names list updated with values like Tom, Dick, and Harry, illustrating append and concatenation operations.

Such side effects can be quite subtle, especially when functions are involved. The expected behaviour of the function print_squares below, is to print the numbers in a list after they’ve been raised to the power of 2. Its main behaviour matches expectation – however , it has a side effect: it also alters the numbers in the original list so their values are lost.

images

Figure 8.7 Altering a single mutable object having multiple names

Diagram: A sequence of three diagrams showing Python list assignments. Step 1 defines notes 1 as Do, Re, Me. Step 2 assigns notes 2 equals notes 1. Step 3 appends Fa to notes 1.

If it were important to preserve the original values of numbers , this program would be faulty. In general, it is best not to alter the value of parameters given to function. A better alternative would be this:

images

images

An object should be immutable unless you have a good reason for it to be mutable.

images

Alternatively, use equivalent immutable data types like tuples (which forbid changes being made in-place). Make sure you know which data types in Python are mutable and which are immutable. Appendix A contains a list of the most common.

Statement ordering

In addition to ever-changing values, program state also requires you to be mindful of instruction ordering. Problems can arise when things are done in the wrong order. For example, this shows two ways of getting your list of numbers doubled:

images

The ‘wrong’ function works incorrectly because numbers in Python are immutable. When you double n , a new value is created that gets the n label. The value that n used to be attached to remains inside the doubles list unchanged.

The ‘right’ function succeeds because it updates the object’s value before adding the resultant value to the list.

Python provides the means for avoiding the kinds of errors caused by statement ordering and explicit managing of state. It allows you to rewrite what would be multi-lined blocks as single, atomic statements that yield the exact same results. For example, let’s rewrite the previous example using a list comprehension (list comprehensions are explained in more detail in the following section More Advanced Constructs):

images

This reduced version of get_doubles is just one line in length instead of five. As written, the list comprehension can be read from left to right as ‘create a new list where each item, n, is multiplied by 2, sourcing the items from another list called singles ’ . A list comprehension manages creation of the list for us. It says only what the resultant list should look like; it says nothing about how to create it.

images

To read more on list comprehensions go here: https://docs.python.org/3/tutorial/datastructures.
html#list-comprehensions

MORE ADVANCED CONSTRUCTS

This section explores some more advanced constructs that allow us to avoid the difficulties presented by statement ordering and the need to continually update values (discussed in the previous section). However, it requires knowledge of the declarative programming style, which we’ll discuss next.

Programming styles: declarative vs imperative

Research shows that programmers instinctively express different parts of their solutions using different styles (Pane et al., 2001). It was demonstrated that two styles of programming featured heavily in the results: declarative and imperative.

Declarative style

Use of this style emphasises declaring what is and isn’t the case in a solution. It uses logical statements to articulate the initial facts and behaviours, as well as the solution’s goals. In other words, it states what the solution does rather than how it does it.

Examples in a Noughts and Crosses game include:

The playing area is a 3 x 3 square.

or:

‘High-score’ is the greatest score in the list of all scores .

images

A popular example of the declarative style is functional programming. This emphasises writing programs made up of mathematical-style functions, which explain what a function does instead of how it does it. It also encourages you to avoid using changeable (i.e. mutable) state.

Imperative style

The imperative style stands in contrast to the declarative approach. It focuses on solving a problem by allowing the author to spell out each step in the algorithm explicitly.

For example:

Play intro sound. Display ‘Player 1 Get Ready.’

or:

Display player’s symbol. Remove arrow pointing at ‘Player 1’. Add arrow pointing at ‘Player 2’. Message = ‘Player 2’s turn.’ Display Message. Wait 5 seconds. Remove Message.

Comparing the styles

Different styles are better suited to certain types of goals. For example:

  • The declarative style works well in setting up the solution scenario and laying out the constraints.
  • The imperative style is used when a programmer needs tight control over the execution of steps, particularly when efficiency or the ordering of instructions is critical.

It might come as an unpleasant surprise to learn that programming languages often primarily support only one style. Most popular languages (like Java, C++, Ruby and JavaScript) are mainly imperative. However, this doesn’t mean using an imperative language restricts you to a 100 per cent imperative style. Boundaries between styles have recently begun to blur and some languages now include limited support for other styles.

Python stands mainly in the imperative camp, but it also supports some elements of other styles. As a demonstration, we’ll consider a program that filters a list of numbers to remove all the odd ones. An imperative solution would look something like this:

images

whereas a declarative solution would look like this:

images

Both solutions have the exact same outcomes, but their styles differ. Instead of telling the computer how to do the filtering (as the former solution does), the latter solution simply asks the in-built filter function 55 to do it for us.

Benefits of the declarative style

Using a declarative style brings certain benefits. First, the programmer rarely has to use state to control the program flow, thus reducing the amount of state you need to keep track of. Second, immutable objects are typically the norm. Third, multi-line code blocks can be reduced to very few (sometimes single) lines of code, making it easier to understand a program.

Even though Python stands mainly in the imperative camp, opportunities to use a declarative approach (like replacing multi-line loops with single-line expressions) will present themselves throughout your programming. It’s a good idea to pursue them because a declarative approach encourages you to break your program into small, reusable functions possessing no side effects. As a consequence:

  • The program will be smaller overall.
  • It will be easier to reason about a program’s behaviour, because its parts are small and self-contained.
  • Testing and debugging become easier.
  • Some functions you create will be generic, allowing you to reuse them and exploit the patterns in your solution.

Let’s look at ways you can replace long, stateful pieces of code with short, stateless alternatives.

Comprehensions

Programs often work with collections, objects that bunch together a load of items. The usual approach to handling collections in an imperative style is to use a loop, but as we’ve seen, this can add complications. What’s more, loops are unintuitive to programming novices.

In reality, people find that the most natural approach to creating a collection is simply to define them into existence. That is, to describe what they should look like, rather than how they should be created. Contrast this declarative statement:

Create a list of all even numbers between 1 and 15.

with its imperative equivalent:

Create a new list, l. Go through each number, n, from 1 to 15. For each n, if n is even, then add it to l.

Python provides a means to apply the more intuitive approach in the form of comprehensions (which we saw a few brief examples of earlier). A comprehension is just a fancy name for a concise way of creating new collections out of existing ones. The following example creates a list of square numbers from a list of numbers:

numbers = [1, 2, 3, 4, 5]

# ‘n ** 2’ = n to the power 2squares = [n ** 2 for n in numbers]
# squares = [1, 4, 9, 16, 25]

You can also filter out unwanted items from the original list by adding an if clause. The next example includes in a new list only four-letter names from the old one, and makes sure that the names are properly capitalised:

images

A set is very much like a list. It collects together a group of items. It differs in a couple of ways, including:

  • A set uses curly brackets instead of squares one, i.e. {1, 2, 3} instead of [1, 2, 3]
  • A set cannot contain repeated items. For example, adding 3 to the list [1, 2] results in [1, 2, 3] and adding 3 to the set {1, 2} results in {1, 2, 3}. However, adding 3 to the list [1, 2, 3] results in [1, 2, 3, 3], whereas adding 3 to the set {1, 2, 3} results in {1, 2, 3} because 3 is already in the set.

A set of strings

forenames = {‘graham’, ‘john’, ‘eric’, ‘terry’ , ‘michael’}

# Set comprehensions work just the same way as list comprehensionsfour_letter_pythons = {name.capitalize() for name in forenames if len(name) == 4 }

# Prints {‘Eric’, ‘John’}
print(four_letter_pythons)

The last example replaces this imperative version:

images

Higher-order functions

Chapter 2 drew an analogy between algorithms and recipes. Both describe a series of steps, each of which manipulate objects in various ways.

Like any analogy, it’s not perfect. Something that the earlier analogy failed to convey is how the list of instructions can be manipulated as an object itself. (I don’t mean by doing something like folding up the paper the recipe is written on and using it as a funnel.) So, let’s extend the analogy.

You need to begin by comparing a computer program (made up of lots of functions) to a recipe book (made up of lots of recipes). Some recipes can be combined with others in different ways. For example, a cake recipe might tell you how to bake a generic cake base and give you the choice of fillings to put in it. Instead of that recipe explaining how to make several different fillings, it would simply refer to ‘the filling’ (‘while the cake is baking prepare the filling’ or ‘spread the filling you made onto the base’). Therefore, the cake recipe is, by itself, incomplete. It only becomes complete when you combine it with another recipe for the filling, which could be blueberry, butterscotch, hot fudge or whatever you fancy.

This way, the filling recipe acts as a parameter to the cake recipe. The cake recipe is generic and (depending on which filling recipe you use) could become a recipe for blueberry cake, butterscotch cake or a hot fudge cake.

Now – assuming your hunger is not distracting you – we’ll see how functions can become parameters to other functions in an analogous way. The following example demonstrates this:

images

Functions that can be treated as objects, like is_positive and is_even , are termed higher-order functions. In this example, the functions is_even and is_positive are the ‘filling’ functions that are passed to another function. The test_numbers function stands in for the generic cake recipe. It tests a series of numbers in a certain way depending on which test function you give it. When you give it the is_even function, it becomes a function for testing whether numbers in a list are even or not. When you give it the is_positive function, it instead reports on which numbers are greater than zero.

A version without higher-order functions or list comprehensions would look something like this:

images

The generic solution reduces the size of the program and reduces the amount of state to manage, not only by using list comprehensions, but also by reducing the number of places where tests are carried out. Imagine both versions above having additional functions added to them. The non-generic version would grow in size much quicker than the generic one.

Functional primitives

When using higher-order functions, three operations in particular get carried out so often that they’ve been given their own names. Together they form the core of a functional programming approach and consequently are sometimes called functional primitives:

  • Map: applies a function to all the items in a collection and puts the results in a new collection.
  • Filter: creates a new collection, including only the items that return True when a testing function is applied to them.
  • Reduce (aka fold): performs an operation on each item in a collection and produces a single result.

Python provides the functional primitives built-in. The following code rewrites an earlier example to use a map .

words = [‘my’, ‘big’, ‘meal’, ‘comes’, ‘mostly’, ‘bearing’ , ‘doubtful’, ‘garnishes’]

lengths = list(map(len, words))
print(lengths) # Prints [2, 3, 4, 5, 6, 7, 8, 9]

We’ve already seen an example of filter in the section ‘Comparing the styles’ earlier in the chapter.

Finally, an example of the reduce function is producing the sum of a list of numbers: 56

images

reduce works by taking a function (like add ) and applying it repeatedly to build up a cumulative value. The function it takes must have two parameters. To the first parameter ( x in this example), reduce assigns the cumulative value. To the second ( y in this example), it assigns the next value from the list. These assignments happen automatically. The function is then executed and the result becomes the updated cumulative value.

In the example above, the cumulative value is a running total. At the start this is 0 and the next value from the list is 1. Executing add(0, 1) yields a running total of 1. Next, add(1, 2) yields 3. Then, add(3, 3) , followed by add(6, 4) , and finally add(10, 5) . The final result of 15 gets assigned to sum .

SUMMARY

All programs, even very large and complex ones, can be built from a relatively small number of distinct building blocks. This chapter discussed the most important fundamental building blocks.

You can make logical decisions in programs, using logical expressions, and even chain them together using logical operators. Logical decisions are incorporated into some of the basic algorithmic constructs (such as if-statements and loops).

In addition to logic, algorithms also allow you to keep track of data that are important to your solution (that is, the state). State in programs must be carefully managed, because mismanagement can easily lead to bugs. The data can be structured in various ways using the different data types available.

Finally, this chapter introduced a few advanced programming styles and constructs that can help you create programs that are less error prone and more easily constructed and maintained.

EXERCISES

EXERCISE 1

Mark the following statements as true or false:

  1. You cannot assign the value of an immutable variable to another variable.
  2. The continue keyword forces a loop to end immediately and continue executing with the code that follows the loop.
  3. Declarative programming is useful when you need careful control over the step-by-step behaviour of a program.
  4. Only one part of a multi-part if-statement can be executed at the most.
  5. An expression is a piece of code that evaluates to a result.

EXERCISE 2

Look again at the example in section ‘Mutability’, where the value of notes_1 is assigned to the variable notes_2 . Rewrite the code so that notes_1 can be updated without simultaneously altering the value of notes_2 .

EXERCISE 3

Take your solution to Chapter 2 , Exercise 5 (write an algorithm for singing The 12 Days of Christmas ). Convert the algorithm into a Python program.

EXERCISE 4

Write a program that takes a list of Fahrenheit measurements and converts it into a list of Celsius measurements.

images

HINT : Converting Fahrenheit to Celsius is done using the following formula: C = F – 32 × 59.

EXERCISE 5

Using the filter function, write a program to filter out annoying words from a list of words, specifically words that are in all upper-case characters and words that end with multiple exclamation marks.