0% found this document useful (0 votes)
30 views

2 Conditional

The document discusses conditional execution in Python using if, elif, else statements and try/except blocks. It also covers short-circuit evaluation and debugging techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

2 Conditional

The document discusses conditional execution in Python using if, elif, else statements and try/except blocks. It also covers short-circuit evaluation and debugging techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CONDITIONAL

EXECUTION
CONDITIONAL EXECUTION
if x > 0 :
print ('x is positive‘)
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 pass statement, which does
nothing.
if x < 0 :
Pass # need to handle negative values!
if x%2 == 0 :
print ('x is even‘)
else :
print ('x is odd‘)
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:
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‘)

elif is an abbreviation of “else if.”


One conditional can also be nested within another. We could have written
the trichotomy example like this:
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‘)
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:
if 0 < x:
if x < 10:
print ('x is a positive single-digit number.‘)
The print statement is executed only if we make it pass both
conditionals, so we can get the same effect with the and
operator:
if 0 < x and x < 10:
print ('x is a positive single-digit number.‘)
CATCHING EXCEPTIONS
Here is a sample program to convert a Fahrenheit temperature to a
Celsius temperature:
inp = input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print (cel)
If 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(): fred
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.

We can rewrite our temperature converter as follows:


inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print (cel)
except:
print (‘You are suppose to enter a number‘)
Python starts by executing the sequence of statements in the try
block. If all goes well, it skips the except block and proceeds. If an
exception occurs in the try block, Python jumps out of the try block
and executes the sequence of statements in the except block.
python fahren2.py
Enter Fahrenheit Temperature:72
22.2222222222
//////////////////////////////////////////////
python fahren2.py
Enter Fahrenheit Temperature:fred
You are suppose to enter a number
Handling an exception with a try statement is called catching an
exception. In this example, the except clause prints an error
message. In general, catching an exception gives you a chance to
fix the problem, or try again, or at least end the program gracefully.
SHORT CIRCUIT EVALUATION
• Short circuit evaluation of logical expressions 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, 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.
• 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.
• 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:
>>> 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 (x/y) and y was
zero which causes a runtime error. But the second example did not fail
because the first part of the expression x >= 2 evaluated to False so the (x/y)
was not ever executed due to the short circuit rule and there was no error.
We can construct the logical expression to strategically place a guard
evaluation just before the evaluation that might cause an error as follows:
>>> 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, x >= 2 is False so the
evaluation stops at the and.

In the second logical expression x >= 2 is True but y != 0 is


False so we never reach (x/y).

In the third logical expression, the y != 0 is after the (x/y)


calculation so the expression fails with an error.

In the second expression, we say that y != 0 acts as a guard


to insure that we only execute (x/y) if y is non-zero.
DEBUGGING
The traceback Python displays when an error occurs contains a lot of
information, The most useful parts are usually:
• What kind of error it was, and
• Where it occurred.
Syntax errors are usually easy to find. Whitespace errors can be tricky
because spaces and tabs are invisible and we are used to ignoring them.
>>> x = 5
>>> y = 6
File "<stdin>", line 1
y=6
^
SyntaxError: invalid syntax
In this example, the problem is that the second line is indented by one
space. But the error message points to y, which is misleading. In general,
error messages indicate where the problem was discovered, but the actual
error might be earlier in the code, sometimes on a previous line.
The same is true of runtime errors. Suppose you are trying to
compute a signal-to noise ratio in decibels. The formula is
SNRdb =10log10(Psignal / Pnoise). In Python, you might write
something like this:

import math
Signal_power = 9
Noise_power = 10
ratio = signal_power / noise_power
decibels = 10 * math.log10(ratio)
print decibels
But when you run it, you get an error message1:
Traceback (most recent call last):
File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio)
OverflowError: math range error
EXERCISES
Exercise 3.1 Rewrite your pay computation to give the employee 1.5
times the hourly rate for hours worked above 40 hours.
Enter Hours: 45
Enter Rate: 10
Pay: 475.0

Exercise 3.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:


Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input
Exercise 3.3 Write a program to prompt for a score between 0.0 and 1.0. If the score
is out of range print an error. If the score is between 0.0 and 1.0, print a grade using
the following table:
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
Run the program repeatedly as shown above to test the various different values for
input.
ADDITIONAL EXERCISES
1. During a special sale at a store, a 10% discount is taken on
purchases over $10.00. Write a Python program that asks for
the amount of purchases, then calculates the discounted price.
The purchase amount will be input in dollars(as an float).
2. Write a Python program that receives the age of the user and
display whether he/she can drive a car. If the user is above 18
years old, he/she can drive.
3. Write a Python program that finds the minimum of three values
a, b and c.
4. Write a Python program that divides two numbers together and
display the result. However if the second number is a zero then
the calculation can't be done as dividing a number by zero
gives a result of infinity.
5. Write a Python program to calculate the water rates for a
customer. All customers are charged a service fee of $100. In
addition domestic customers “D” are charged $0.01 per liter
and commercial customers “C” $0.02 per liter of water used.

You might also like