## Exercises

1. Implement a Tribool data type. This is a data type that can have one of three values: True, False, or unknown (for which you should use None). In addition to_init_(), implement_str_(),_repr_(), and_cmp_();

also, implement_nonzero_() for conversion to bool(),_invert_() for logical not (~),_and_() for logical and (&), and_or_() for logical or (|).

There are two possible logics that can be used: propagating, where any expression involving unknown (i.e., None) is unknown, and nonpropagating, where any expression involving unknown that can be evaluated is evaluated. Use nonpropagating logic so that your Tribools match the truth table shown here, and where t is Tribool(True), f is Tribool(False), and n is Tribool(None) (for unknown):

 Expression Result Expression Result Expression Result ~t False ~f True ~n None t & t True t & f False t & n None f & f False f & n False n & n None t | t True t I f True t I n True f I f False f I n None n I n None

For example, with nonpropagating logic, True | None is True, because as long as one operand to logical or is true, the expression is true. But False | None is None (unknown), because we cannot determine the result.

Most of the methods can be implemented in just a few lines of code. Make sure that you use the doctest module and write unit tests for all the methods.

2. Implement a Stack class and an EmptyStackError exception class. The Stack class should use a list to store its items, and should provide pop() to return and remove the item at the top of the stack (the rightmost item), top() to return the item at the top of the stack, and push() to push a new item onto the stack. Also provide special methods so that len() and str() will work sensibly. Make sure that pop() and top() raise EmptyStackError if the stack is empty when they are called. The methods can be written using very few lines of code. Make sure that you use the doctest module and write unit tests for all the methods.

The model answers are provided in the files chap03/tribool.py and chap03/

stack.py.

Part II

Basic GUI Programming

• An Expression Evaluator in 30 Lines

• A Currency Converter in 70 Lines

• Signals and Slots 