Control Structures

Like all programming languages, Python has a boolean type (with True and False being the only two possible boolean values). A comparison (e.g. 5==5, 2>3, etc.) evaluates to a boolean. Boolean can be combined (using Boolean Algebra) using the and, or or not logical operators. This is explained in Chapter 4 of the book.

People use boolean expressions in general to write conditional statements (e.g. if, if/else and variations like chained conditionals / nested conditionals).

Work out exercises 1-7 in Chapter 4 of the book. Note that question question 2 starts at the line “if x < y:” and question 5 at the line “if choice == ‘a’:”.

Type conversion

Python is a strongly typed programming language. Yet, it allows the conversion of values of one type into another. For example, int(“42”) evaluates to 42 (an integer). Python provides int(), float(), str() and bool().

Work out exercise 8.

Note that we are skipping GASP (Graphics API for Students of Python) for the time being. We’ll come back to it in a later session.

Fruitful functions

As mentioned in Chapter 5 of the book, the built-in functions we have used, such as abs, pow, and max, have produced results. Calling each of these functions generates a value, which we usually assign to a variable or use as part of an expression. As from now, we are going to write functions that return values.

Remember we wrote a function called distance in the previous session? Modify it to return the distance instead of displaying it. Use that function to implement the function area found in section 5.3 of the book.

Like many programming languages with a LISP heritage, Python allows functions to be passed as parameters to other functions. This is called higher-order programming and is explained in section 5.4.

Unit-testing (using doctest and explained in section 5.8) allows programmers to test the code written easily.

Work out the nine exercises found at the end of Chapter 5. In case you don’t have time to finish in class, do it at home and don’t hesitate to contact us if you are stuck.