Testing your code is a good idea because it usually leads to great improvements. There's many libraries in python that will help with testing but a favourable on called pytest. In this series of videos we demonstrate how the use it.
The folder structure should now look like this;
├── blackjack │ ├── __init__.py │ └── common.py ├── setup.py └── tests ├── __init__.py └── test_blackjack.py
__init__.py files should be empty.
def card_score(cards): if not isinstance(cards, str): raise ValueError("The input for `card_score` needs to be a string.") if len(cards) < 2: raise ValueError("The `card_score` function requires at least 2 cards.") numbers = [c for c in cards if c in "23456789"] faces = [c for c in cards if c in "JQK"] n_aces = sum([1 for c in cards if c == "A"]) score = sum([int(i) for i in numbers]) + len(faces) * 10 while n_aces > 0: score += 1 if score + 11 > 21 else 11 n_aces -= 1 return score if score <= 21 else 0
import pytest from blackjack.common import card_score @pytest.mark.parametrize("cards,score", [('JK', 20), ('KKK', 0), ('AA', 12), ('AK', 21)]) def test_simple_usecase(cards, score): assert card_score(cards) == score
To be able to work on the package in developer mode you'll need to run;
python setup.py develop
And from here you can safely run pytest again.
Feedback? See an issue? Something unclear? Feel free to mention it here.
If you want to be kept up to date, consider getting the newsletter.