Programming 1
Week 7: Notes

Some of this week's topics are covered in Introduction to Computation:

And in Introducing Python:

Here are some additional notes.

Assertions

In Python, the assert statement checks that a given condition is true. If it is false, the program will fail with an AssertionError. For example:

assert 0.0 <= prob <= 1.0

You may add an optional string which will be printed if the assertion fails:

assert 0.0 <= prob <= 1.0, 'probability must be between 0.0 and 1.0'

You can use assertions to verify conditions that should always be true unless there is a bug in the code. If such a condition is false, it is best to find out about it right away, rather than continuing to run and producing an incorrect result later, which may be difficult to debug.

You may also wish to use assertions to verify that arguments passed to a function are valid. For example:

# Compute the average value of numbers in list a

def avg(a):

  assert len(a) > 0, 'list must be non-empty'


  return sum(a) / len(a)

Conditional expressions

In Python, you may use if and else inside an expression; this is called a conditional expression.

For example, consider this code:

if x > 100:

  print('x is big')

else:

  print('x is not so big')

We may rewrite it using a conditional expression:

print('x is ' + ('big' if x > 100 else 'not so big'))

As another example, here is a function that takes two integers and returns whichever has the greater magnitude (i.e. absolute value):

def greater(i, j):

 if abs(i) >= abs(j):
   return i
 else:
   return j

We can rewrite it using a conditional expression:

def greater(i, j):
  return i if abs(i) >= abs(j) else j

(If you already know C or another C-like language, you may notice this feature's resemblance to the ternary operator (? :) in those languages.)