>>> 5 == 5 True >>> 5 == 6 False

>>> type(True) <type 'bool'> >>> type(False) <type 'bool'>The

x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y x is y # x is the same as y x is not y # x is not the same as yAlthough these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign (

is true only if

Finally, the

Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as "true."

>>> 17 and True TrueThis flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).

if x > 0 : print 'x is positive'The boolean expression after the

If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped.

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven't written yet). In that case, you can use the

if x < 0 : pass # need to handle negative values!If you enter an if statement in the Python interpreter, the prompt will change from three chevrons to three dots to indicate you are in the middle of a block of statements as shown below:

>>> x = 3 >>> if x < 10: ... print 'Small' ... Small >>>

if x%2 == 0 : print 'x is even' else : print 'x is odd'If the remainder when

Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called

if x < y: print 'x is less than y' elif x > y: print 'x is greater than y' else: print 'x and y are equal'

There is no limit on the number of

if choice == 'a': print 'Bad guess' elif choice == 'b': print 'Good guess' elif choice == 'c': print 'Close, but not correct'Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

if x == y: print 'x and y are equal' else: if x < y: print 'x is less than y' else: print 'x is greater than y'The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another

Although the indentation of the statements makes the structure apparent,

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

if 0 < x: if x < 10: print 'x is a positive single-digit number.'The

if 0 < x and x < 10: print 'x is a positive single-digit number.'

`raw_input`

and
>>> speed = raw_input(prompt) What...is the airspeed velocity of an unladen swallow? What do you mean, an African or a European swallow? >>> int(speed) ValueError: invalid literal for int() >>>When we are executing these statements in the Python interpreter, we get a new prompt from the interpreter, think "oops" and move on to our next statement.

However if this code is placed in a Python script and this error occurs, your script immediately stops in its tracks with a traceback. It does not execute the following statement.

Here is a sample program to convert a Fahrenheit temperature to a Celsius temperature:

inp = raw_input('Enter Fahrenheit Temperature:') fahr = float(inp) cel = (fahr - 32.0) * 5.0 / 9.0 print celIf we execute this code and give it invalid input, it simply fails with an unfriendly error message:

python fahren.py Enter Fahrenheit Temperature:72 22.2222222222 python fahren.py Enter Fahrenheit Temperature:fred Traceback (most recent call last): File "fahren.py", line 2, in <module> fahr = float(inp) ValueError: invalid literal for float(): fredThere is a conditional execution structure built into Python to handle these types of expected and unexpected errors called "try / except". The idea of

You can think of the

We can rewrite our temperature converter as follows:

inp = raw_input('Enter Fahrenheit Temperature:') try: fahr = float(inp) cel = (fahr - 32.0) * 5.0 / 9.0 print cel except: print 'Please enter a number'Python starts by executing the sequence of statements in the

python fahren2.py Enter Fahrenheit Temperature:72 22.2222222222 python fahren2.py Enter Fahrenheit Temperature:fred Please enter a numberHandling an exception with a

When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it stops its evaluation and does not do the computations in the rest of the logical expression. When the evaluation of a logical expression stops because the overall value is already known, it is called

While this may seem like a fine point, the short circuit behavior leads to a clever technique called the

>>> x = 6 >>> y = 2 >>> x >= 2 and (x/y) > 2 True >>> x = 1 >>> y = 0 >>> x >= 2 and (x/y) > 2 False >>> x = 6 >>> y = 0 >>> x >= 2 and (x/y) > 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero >>>The third calculation failed because Python was evaluating

We can construct the logical expression to strategically place a

>>> x = 1 >>> y = 0 >>> x >= 2 and y != 0 and (x/y) > 2 False >>> x = 6 >>> y = 0 >>> x >= 2 and y != 0 and (x/y) > 2 False >>> x >= 2 and (x/y) > 2 and y != 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero >>>In the first logical expression,

In the third logical expression, the

In the second expression, we say that

- What kind of error it was, and

- Where it occurred.

>>> x = 5 >>> y = 6 File "<stdin>", line 1 y = 6 ^ SyntaxError: invalid syntaxIn this example, the problem is that the second line is indented by one space. But the error message points to

The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio in decibels. The formula is

import math signal_power = 9 noise_power = 10 ratio = signal_power / noise_power decibels = 10 * math.log10(ratio) print decibelsBut when you run it, you get an error message

Traceback (most recent call last): File "snr.py", line 5, in ? decibels = 10 * math.log10(ratio) OverflowError: math range errorThe error message indicates line 5, but there is nothing wrong with that line. To find the real error, it might be useful to print the value of

In general, error messages tell you where the problem was discovered, but that is often not where it was caused.

**body:**- The sequence of statements within a compound statement.

**boolean expression:**- An expression whose value is either
`True`or`False`.

**branch:**- One of the alternative sequences of statements in
a conditional statement.

**chained conditional:**- A conditional statement with a series
of alternative branches.

**comparison operator:**- One of the operators that compares
its operands:
`==`,`!=`,`>`,`<`,`>=`, and`<=`.

**conditional statement:**- A statement that controls the flow of
execution depending on some condition.

**condition:**- The boolean expression in a conditional statement
that determines which branch is executed.

**compound statement:**- A statement that consists of a header
and a body. The header ends with a colon (:). The body is indented
relative to the header.

**guardian pattern:**- Where we construct a logical expression
with additional
comparisons to take advantage of the short circuit behavior.

**logical operator:**- One of the operators that combines boolean
expressions:
`and`,`or`, and`not`.

**nested conditional:**- A conditional statement that appears
in one of the branches of another conditional statement.

**traceback:**- A list of the functions that are executing,
printed when an exception occurs.

**short circuit:**- When Python is part-way through evaluating a logical expression and stops the evaluation because Python knows the final value for the expression without needing to evaluate the rest of the expression.

Enter Hours: 45 Enter Rate: 10 Pay: 475.0

Enter Hours: 20 Enter Rate: nine Error, please enter numeric input Enter Hours: forty Error, please enter numeric input

Score Grade >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F Enter score: 0.95 A Enter score: perfect Bad score Enter score: 10.0 Bad score Enter score: 0.75 C Enter score: 0.5 F

- 1
- In Python 3.0, you no longer get an error message; the division operator performs floating-point division even with integer operands.