Lecture04 Conditionalexecution
Lecture04 Conditionalexecution
Boolean expressions
Logical operators
Conditional execution
Alternative execution
Chained conditionals
Nested conditionals
Catching exceptions using try and except
Short-circuit evaluation of logical expressions
Exercises
Boolean expressions
True and False are special values that belong to the class bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
Boolean expressions
Although these operations are probably familiar to you, the Python symbols are different from the
mathematical symbols for the same operations.
A common error is to use a single equal sign (=) instead of a double equal sign (==).
Remember that = is an assignment operator and == is a comparison operator.
There is no such thing as =< or =>.
Logical operators
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
True
This flexibility can be useful, but there are some situation to it that
might be confusing.
Conditional execution
In order to write useful programs, we almost always need the ability to check conditions and change the
behavior of the program accordingly.
Conditional statements give us this ability. The simplest form is the if statement:
If the logical condition is true, then the indented statement gets executed.
If the logical condition is false, the indented statement is skipped.
if statements have the same structure as function definitions or for loops.
The statement consists of a header line that ends with the colon character (:) followed by an indented block.
Statements like this are called compound statements because they stretch across more than one line.
There is no limit on the number of statements that can appear in the body, but there must be at least one.
It is useful to have a body with no statements. In that case, you can use the pass statement, which does
nothing.
Conditional execution
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:
Alternative execution
A second form of the if statement is alternative execution, in which there are two possibilities and the
condition determines which one gets executed.
The syntax looks like this:
If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays a message to that effect.
If the condition is false, the second set of statements is executed
Since the condition must either be true or false, exactly one of the alternatives will
be executed. The alternatives are called branches, because they are branches in the
flow of execution
Chained conditionals
Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional:
elif is an abbreviation of “else if.” Again, exactly one branch will be executed.
Chained conditionals
There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn’t have to be one.
Although the indentation of the statements makes the structure apparent, nested conditionals become
difficult to read very quickly. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements.
For example, we can rewrite the following code using a single conditional
Catching exceptions using try and except
Earlier we saw a code segment where we used the input and int functions to read and parse an integer
number entered by the user.
We also saw how danger doing this could be:
Catching exceptions using try and except
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 you place this code 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.
Catching exceptions using try and except
If we execute this code and give it invalid input, it simply fails with an unfriendly error message:
Catching exceptions using try and except
There is a conditional execution structure built into Python to handle these types of expected and unexpected
errors called “try / except”.
The idea of try and except is that you know that some sequence of instruction(s) may have a problem and
you want to add some statements to be executed if an error occurs.
These extra statements (the except block) are ignored if there is no error.
Catching exceptions using try and except
You can think of the try and except feature in Python as an “insurance policy” on a sequence of statements.
We can rewrite our temperature converter as follows:
Catching exceptions using try and except
When Python is processing a logical expression such as x >= 2 and (x/y) > 2, it evaluates the expression
from left to right.
Because of the definition of and, if x is less than 2, the expression x >= 2 is False and so the whole
expression is False regardless of whether (x/y) > 2 evaluates to True or False.
Short-circuit evaluation of logical expressions
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
short-circuiting the evaluation.
Short-circuit evaluation of logical expressions
While this may seem like a fine point, the short-circuit behavior leads to a clever technique called the
guardian pattern.
Consider the following code sequence in the Python interpreter:
The third calculation failed because Python was evaluating (x/y) and
y was zero, which causes a runtime error.
But the first and the second examples did not fail because in the first
calculation y was non zero and in the second one the first part of
these expressions x >= 2 evaluated to False so the (x/y) was not ever
executed due to the short-circuit rule and there was no error.
Short-circuit evaluation of logical expressions
We can construct the logical expression to strategically place a guard evaluation just before the evaluation
that might cause an error as follows:
Exercise 1:
Please calculate payment using hours and hourly rate.
Calculate payment using 1.5 times the hourly rate if employee worked above 40 hours.
Exercises
Exercise 2:
Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by
printing a message and exiting the program.
The following shows two executions of the program:
Exercises
Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error
message. If the score is between 0.0 and 1.0, print a grade using the following table:
Thank you for listening…