Project 1 · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
import itertools

class Account:
    counter = itertools.count(1)

    def new_id(self):
        return next(Account.counter)

a, b = Account(), Account()
print(a.new_id(), b.new_id(), a.new_id())
2. What does this print?
class Account:
    interest_rate = 0.5

a1, a2 = Account(), Account()
a1.interest_rate = 10
Account.interest_rate = 2
print(a1.interest_rate, a2.interest_rate)
3. What does this print?
class Account:
    _rate = 0.5

    @classmethod
    def set_rate(cls, value):
        cls._rate = value

a1, a2 = Account(), Account()
a1.set_rate(3)
print(Account._rate, a2._rate, '_rate' in a1.__dict__)
4. Why is parse_confirmation_code best written as a @staticmethod?
5. What does this print?
class Person:
    def __init__(self, name):
        self.name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if not value.strip():
            raise ValueError('empty name')
        self._name = value.strip()

try:
    p = Person('   ')
    print('created', repr(p.name))
except ValueError as ex:
    print('ValueError:', ex)
6. What does this print?
from datetime import timedelta

print(timedelta(hours=-1, minutes=30) == timedelta(minutes=-30))
7. How many times is setup printed?
import io, unittest

class T(unittest.TestCase):
    def setUp(self):
        print('setup')
    def test_a(self):
        pass
    def test_b(self):
        self.assertTrue(False)
    def helper(self):
        pass

suite = unittest.TestLoader().loadTestsFromTestCase(T)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
8. A test does with self.assertRaises(TypeError): Account(...), but the code actually raises ValueError. How does unittest report the test?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: The TimeZone class

Complete the TimeZone class.

- TimeZone(name, offset_hours, offset_minutes). Store the name stripped of surrounding whitespace. - Raise ValueError if the name is None, empty or only whitespace; if either offset isn't an integer (numbers.Integral); if the minutes are outside -59...59; or if the combined offset timedelta(hours=offset_hours, minutes=offset_minutes) is outside -12:00...+14:00 (both ends allowed). - Read-only properties name and offset (a timedelta). Assigning to them must raise AttributeError. - __eq__: equal when the other object is a TimeZone with the same name, hours and minutes. Comparing with any other type gives False. - __repr__ returns exactly TimeZone(name='ABC', offset_hours=-2, offset_minutes=-15) (for that example).

Hints (3)
  1. Store the values in "private" attributes (_name, _offset, ...) and expose them with getter-only @property methods.
  2. timedelta objects compare with < and >, so offset < timedelta(hours=-12) checks the lower bound.
  3. In __eq__, check isinstance(other, TimeZone) first, then compare the fields with and so the evaluation short-circuits.
Show a solution
import numbers
from datetime import timedelta

class TimeZone:
    def __init__(self, name, offset_hours, offset_minutes):
        if name is None or len(str(name).strip()) == 0:
            raise ValueError('Timezone name cannot be empty.')
        if not isinstance(offset_hours, numbers.Integral):
            raise ValueError('Hour offset must be an integer.')
        if not isinstance(offset_minutes, numbers.Integral):
            raise ValueError('Minutes offset must be an integer.')
        if offset_minutes < -59 or offset_minutes > 59:
            raise ValueError('Minutes offset must be between -59 and 59.')
        offset = timedelta(hours=offset_hours, minutes=offset_minutes)
        if offset < timedelta(hours=-12) or offset > timedelta(hours=14):
            raise ValueError('Offset must be between -12:00 and +14:00.')
        self._name = str(name).strip()
        self._offset_hours = offset_hours
        self._offset_minutes = offset_minutes
        self._offset = offset

    @property
    def name(self):
        return self._name

    @property
    def offset(self):
        return self._offset

    def __eq__(self, other):
        return (isinstance(other, TimeZone) and
                self.name == other.name and
                self._offset_hours == other._offset_hours and
                self._offset_minutes == other._offset_minutes)

    def __repr__(self):
        return (f"TimeZone(name='{self.name}', "
                f"offset_hours={self._offset_hours}, "
                f"offset_minutes={self._offset_minutes})")

Exercise 2: The account holder

The TimeZone class is provided. Write the start of the Account class:

- Account(account_number, first_name, last_name, timezone=None) - account_number: a read-only property. - first_name and last_name: read/write properties. The setter strips surrounding whitespace and raises ValueError for None, empty or blank values, both in __init__ and on later assignment. - full_name: a read-only computed property, 'first last', always up to date. - timezone: read/write property that defaults to TimeZone('UTC', 0, 0). Assigning anything that isn't a TimeZone raises ValueError.

Hints (3)
  1. In __init__, assign self.first_name = first_name (not self._first_name) so the setter's validation runs.
  2. Both name setters need the same check. Put it in one @staticmethod that validates and returns the stripped value.
  3. Default timezone=None in the signature and create TimeZone('UTC', 0, 0) inside __init__.
Show a solution
import numbers
from datetime import timedelta

class TimeZone:
    def __init__(self, name, offset_hours, offset_minutes):
        if name is None or len(str(name).strip()) == 0:
            raise ValueError('Timezone name cannot be empty.')
        self._name = str(name).strip()

        if not isinstance(offset_hours, numbers.Integral):
            raise ValueError('Hour offset must be an integer.')
        if not isinstance(offset_minutes, numbers.Integral):
            raise ValueError('Minutes offset must be an integer.')
        if offset_minutes < -59 or offset_minutes > 59:
            raise ValueError('Minutes offset must be between -59 and 59 (inclusive).')

        offset = timedelta(hours=offset_hours, minutes=offset_minutes)
        # real-world UTC offsets range from -12:00 to +14:00
        if offset < timedelta(hours=-12) or offset > timedelta(hours=14):
            raise ValueError('Offset must be between -12:00 and +14:00.')

        self._offset_hours = offset_hours
        self._offset_minutes = offset_minutes
        self._offset = offset

    @property
    def offset(self):
        return self._offset

    @property
    def name(self):
        return self._name

    def __eq__(self, other):
        return (isinstance(other, TimeZone) and
                self.name == other.name and
                self._offset_hours == other._offset_hours and
                self._offset_minutes == other._offset_minutes)

    def __repr__(self):
        return (f"TimeZone(name='{self.name}', "
                f"offset_hours={self._offset_hours}, "
                f"offset_minutes={self._offset_minutes})")


class Account:
    def __init__(self, account_number, first_name, last_name, timezone=None):
        self._account_number = account_number
        self.first_name = first_name
        self.last_name = last_name
        if timezone is None:
            timezone = TimeZone('UTC', 0, 0)
        self.timezone = timezone

    @property
    def account_number(self):
        return self._account_number

    @property
    def first_name(self):
        return self._first_name

    @first_name.setter
    def first_name(self, value):
        self._first_name = Account.validate_name(value, 'First name')

    @property
    def last_name(self):
        return self._last_name

    @last_name.setter
    def last_name(self, value):
        self._last_name = Account.validate_name(value, 'Last name')

    @property
    def full_name(self):
        return f'{self.first_name} {self.last_name}'

    @property
    def timezone(self):
        return self._timezone

    @timezone.setter
    def timezone(self, value):
        if not isinstance(value, TimeZone):
            raise ValueError('Time zone must be a valid TimeZone object.')
        self._timezone = value

    @staticmethod
    def validate_name(value, field_title):
        if value is None or len(str(value).strip()) == 0:
            raise ValueError(f'{field_title} cannot be empty.')
        return str(value).strip()

Exercise 3: Balance and a shared interest rate

Here is a cut-down Account (just an account number and a balance) so you can focus on two pieces:

1. Balance. Account(account_number, initial_balance=0) stores the balance as a float, exposed through a read-only balance property. Raise ValueError if initial_balance isn't a real number (numbers.Real) or is negative. 2. Interest rate. A class attribute _interest_rate = 0.5 (percent), shared by all accounts, with two class methods: get_interest_rate() and set_interest_rate(value). The setter raises ValueError for non-real or negative values. Calling the setter through an instance must change the rate for every account.

Hints (3)
  1. A getter-only @property named balance, backed by self._balance, makes the balance read-only.
  2. isinstance(value, numbers.Real) accepts ints and floats but rejects strings, None and complex numbers.
  3. In a @classmethod, assign cls._interest_rate = value. cls is the class even when the method is called through an instance.
Show a solution
import numbers

class Account:
    _interest_rate = 0.5  # percent

    def __init__(self, account_number, initial_balance=0):
        self.account_number = account_number
        if not isinstance(initial_balance, numbers.Real):
            raise ValueError('Initial balance must be a real number.')
        if initial_balance < 0:
            raise ValueError('Initial balance cannot be negative.')
        self._balance = float(initial_balance)

    @property
    def balance(self):
        return self._balance

    @classmethod
    def get_interest_rate(cls):
        return cls._interest_rate

    @classmethod
    def set_interest_rate(cls, value):
        if not isinstance(value, numbers.Real):
            raise ValueError('Interest rate must be a real number.')
        if value < 0:
            raise ValueError('Interest rate cannot be negative.')
        cls._interest_rate = value

Exercise 4: Transactions and confirmation codes

This cut-down Account already has a read-only balance, the shared transaction_counter, the _interest_rate (percent), the _transaction_codes table and a validate_real_number helper. Write:

- generate_confirmation_code(self, transaction_code): returns '<code>-<account_number>-<YYYYMMDDHHMMSS>-<id>', using the current UTC time (datetime.now(timezone.utc)) and the next value of Account.transaction_counter. - deposit(value): validate (a real number, at least 0.01), add to the balance, return a D code. - withdraw(value): validate the same way. If the balance would go negative, return an X code and leave the balance unchanged; otherwise subtract and return a W code. - pay_interest(): add balance * rate / 100 to the balance and return an I code.

Invalid amounts raise ValueError without changing the balance.

Hints (3)
  1. datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S') gives the timestamp, and next(Account.transaction_counter) the next id.
  2. Every transaction method validates first, then generates the code, then updates the balance, then returns the code.
  3. A declined withdrawal still generates (and returns) a confirmation code, with the 'rejected' transaction code.
Show a solution
import itertools
import numbers
from datetime import datetime, timezone

class Account:
    transaction_counter = itertools.count(100)
    _interest_rate = 0.5  # percent
    _transaction_codes = {'deposit': 'D', 'withdraw': 'W',
                          'interest': 'I', 'rejected': 'X'}

    def __init__(self, account_number, initial_balance=0):
        self._account_number = account_number
        self._balance = float(Account.validate_real_number(initial_balance, min_value=0))

    @property
    def account_number(self):
        return self._account_number

    @property
    def balance(self):
        return self._balance

    @staticmethod
    def validate_real_number(value, min_value=None):
        if not isinstance(value, numbers.Real):
            raise ValueError('Value must be a real number.')
        if min_value is not None and value < min_value:
            raise ValueError(f'Value must be at least {min_value}.')
        return value

    def generate_confirmation_code(self, transaction_code):
        dt_str = datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')
        transaction_id = next(Account.transaction_counter)
        return f'{transaction_code}-{self.account_number}-{dt_str}-{transaction_id}'

    def deposit(self, value):
        value = Account.validate_real_number(value, min_value=0.01)
        conf_code = self.generate_confirmation_code(Account._transaction_codes['deposit'])
        self._balance += value
        return conf_code

    def withdraw(self, value):
        value = Account.validate_real_number(value, min_value=0.01)
        if self.balance - value < 0:
            return self.generate_confirmation_code(Account._transaction_codes['rejected'])
        conf_code = self.generate_confirmation_code(Account._transaction_codes['withdraw'])
        self._balance -= value
        return conf_code

    def pay_interest(self):
        interest = self.balance * Account._interest_rate / 100
        conf_code = self.generate_confirmation_code(Account._transaction_codes['interest'])
        self._balance += interest
        return conf_code

Exercise 5: Parsing a confirmation code

TimeZone and the Confirmation namedtuple are provided. Add a static method Account.parse_confirmation_code(confirmation_code, preferred_time_zone=None) that returns a Confirmation with:

- account_number, transaction_code, transaction_id: strings taken from the code - time_utc: the UTC time in ISO format, e.g. '2019-03-15T14:59:00' - time: the time shifted by the time zone's offset, as '2019-03-15 07:59:00 (MST)'

The time zone defaults to TimeZone('UTC', 0, 0). Raise ValueError if the code doesn't have exactly four dash-separated parts, if the timestamp isn't a valid YYYYMMDDHHMMSS date and time, or if the time zone isn't a TimeZone.

Hints (3)
  1. Split on '-', check the length, then unpack: transaction_code, account_number, raw_dt_utc, transaction_id = parts.
  2. datetime.strptime(raw, '%Y%m%d%H%M%S') parses the timestamp and raises ValueError if it's invalid. .isoformat() gives time_utc.
  3. The local time is dt_utc + tz.offset; format it with strftime('%Y-%m-%d %H:%M:%S') and append the zone name in parentheses.
Show a solution
import numbers
from collections import namedtuple
from datetime import datetime, timedelta

class TimeZone:
    def __init__(self, name, offset_hours, offset_minutes):
        if name is None or len(str(name).strip()) == 0:
            raise ValueError('Timezone name cannot be empty.')
        self._name = str(name).strip()

        if not isinstance(offset_hours, numbers.Integral):
            raise ValueError('Hour offset must be an integer.')
        if not isinstance(offset_minutes, numbers.Integral):
            raise ValueError('Minutes offset must be an integer.')
        if offset_minutes < -59 or offset_minutes > 59:
            raise ValueError('Minutes offset must be between -59 and 59 (inclusive).')

        offset = timedelta(hours=offset_hours, minutes=offset_minutes)
        # real-world UTC offsets range from -12:00 to +14:00
        if offset < timedelta(hours=-12) or offset > timedelta(hours=14):
            raise ValueError('Offset must be between -12:00 and +14:00.')

        self._offset_hours = offset_hours
        self._offset_minutes = offset_minutes
        self._offset = offset

    @property
    def offset(self):
        return self._offset

    @property
    def name(self):
        return self._name

    def __eq__(self, other):
        return (isinstance(other, TimeZone) and
                self.name == other.name and
                self._offset_hours == other._offset_hours and
                self._offset_minutes == other._offset_minutes)

    def __repr__(self):
        return (f"TimeZone(name='{self.name}', "
                f"offset_hours={self._offset_hours}, "
                f"offset_minutes={self._offset_minutes})")


Confirmation = namedtuple(
    'Confirmation',
    'account_number transaction_code transaction_id time_utc time'
)


class Account:
    @staticmethod
    def parse_confirmation_code(confirmation_code, preferred_time_zone=None):
        parts = confirmation_code.split('-')
        if len(parts) != 4:
            raise ValueError('Invalid confirmation code.')
        transaction_code, account_number, raw_dt_utc, transaction_id = parts

        try:
            dt_utc = datetime.strptime(raw_dt_utc, '%Y%m%d%H%M%S')
        except ValueError as ex:
            raise ValueError('Invalid transaction datetime.') from ex

        if preferred_time_zone is None:
            preferred_time_zone = TimeZone('UTC', 0, 0)
        if not isinstance(preferred_time_zone, TimeZone):
            raise ValueError('Invalid TimeZone specified.')

        dt_preferred = dt_utc + preferred_time_zone.offset
        dt_preferred_str = (f"{dt_preferred.strftime('%Y-%m-%d %H:%M:%S')} "
                            f"({preferred_time_zone.name})")
        return Confirmation(account_number, transaction_code, transaction_id,
                            dt_utc.isoformat(), dt_preferred_str)