Spaces are used sparingly in Python. It is common to put spaces around the assignment operator. The recommended style is
c = (f-32)*5/9
Do not take great pains to line up assignment operators vertically. The following has too much space, and is hard to read, even though it is fussily aligned.
a = 12
b = a*math.log(a)
aVeryLongVariable = 26
d = 13
This is considered poor form because Python takes a lot of its look from natural languages and mathematics. This kind of horizontal whitespace is hard to follow: it can get difficult to be sure which expression lines up with which variable. Python programs are meant to be reasonably compact, more like reading a short narrative paragraph or short mathematical formula than reading a page-sized UML diagram.
Variable names are often given asmixedCase; variable names typically begin with lower-case letters. The lower_case_with_underscoresstyle is also used, but is less popular.
In addition, the following special forms using leading or trailing underscores are recognized:
• single_trailing_underscore_: used to avoid conflicts with Python keywords. For example: ‘print_ = 42’
• __double_leading_and_trailing_underscore__: used for special objects or attributes, e.g. __init__, __dict__ or __file__. These names are reserved; do not use names like these in your programs unless you specifically mean a particular built-in feature of Python.
• _single_underscore: means that the variable is “private”.
EIGHT
TRUTH, COMPARISON AND
CONDITIONAL PROCESSING
Truth, Comparison and the if Statement, pass and assert Statements.
Leading up to theforandwhile Statements Also, thebreakandcontinue.
The elements of Python we’ve seen so far give us some powerful capabilities. We can write programs that implement a wide variety of requirements. State change is not always as simple as the examples we’ve seen in Variables, Assignment and Input. When we run a script, all of the statements are executed unconditionally. Our programs can’t handle alternatives or conditions.
Python provides decision-making mechanisms similar to other programming languages. InTruth and Logic we’ll look at truth, logic and the logic operators. The exercises that follow examine some subtleties of Python’s evaluation rules. In Comparisons we’ll look at the comparison operators. Then, Conditional Processing: the if Statement describes the if statement. In The assert Statement we’ll introduce a handy diagnostic tool, theassertstatement.
In the next chapter,Loops and Iterative Processing, we’ll look at looping constructs.
8.1 Truth and Logic
Many times the exact change in state that our program needs to make depends on a condition. A condition is a Boolean expression; an expression that is eitherTrueorFalse. Generally conditions are on comparisons among variables using the comparison operations.
We’ll look at the essential definitions of truth, the logic operations and the comparison operations. This will allow us to build conditions.
8.1.1 Truth
Python represents truth and falsity in a variety of ways.
• False. Also 0, the special valueNone, zero-length strings "", zero-length lists[], zero-length tuples (), empty mappings{}are all treated asFalse.
• True. Anything else that is not equivalent toFalse.
We try to avoid depending on relatively obscure rules for determining True vs. False. We prefer to use the two explicit keywords,True andFalse. Note that a previous version of Python didn’t have the boolean literals, and some older open-source programs will define these values.
Python provides a factory function to collapse these various forms of truth into one of the two explicit boolean objects.
bool(object)
ReturnsTruewhen the argumentobjectis one the values equivalent to truth,Falseotherwise.
8.1.2 Logic
Python provides three basic logic operators that work on this Boolean domain. Note that this Boolean domain, with just two values,TrueandFalse, and these three operators form a complete algebraic system, sometimes called Boolean algebra, after the mathemetician George Boole. The operators supported by Python arenot,andandor. We can fully define these operators with rule statements or truth tables. This truth table shows the evaluation of notx.
print "x", "not x" print True, not True print False, not False
x not x
True False False True
This table shows the evaluation ofx andy for all combination ofTrue andFalse. print "x", "y", "x and y"
print True, True, True and True print True, False, True and False print False, True, False and True print False, False, False and False
x y x and y
True True True True False False False True False False False False
An important feature of and is that it does not evaluate all of its parameters before it is applied. If the left-hand side isFalseor one of the equivalent values, the right-hand side is not evaluated, and the left-hand value is returned. We’ll look at some examples of this later.
For now, you can try things like the following. print False and 0
print 0 and False
This will show you that the first false value is what Python returns forand. This table shows the evaluation ofx ory for all combination of TrueandFalse.
x y x or y
True True True True False True False True True False False False
As a final note, and is a high priority operator (analogous to multiplication) and or is lower priority (analogous to addition). When evaluating expressions like ‘a or b and c’, theand operation is evaluated first, followed by theoroperation.
8.1.3 Exercises
1. Logic Short-Cuts. We have several versions of false: False,0,None,'',(),[]and{}. We’ll cover all of the more advanced versions of false in Data Structures. For each of the following, work out the value according to the truth tables and the evaluation rules. Since each truth or false value is unique, we can see which part of the expression was evaluated.
• ‘False and None’
• ‘0 and None or () and []’ • ‘True and None or () and []’ • ‘0 or None and () or []’ • ‘True or None and () or []’ • ‘1 or None and 'a' or 'b'’