2 Conditional
2 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‘)
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.