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 files are now updated.
def card_score(cards): if len(cards) < 2: raise ValueError("The `card_score` function requires at least 2 cards.") if not isinstance(cards, str): raise ValueError("The input for `card_score` needs to be a string.") 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 def test_raise_error(): with pytest.raises(ValueError): card_score("")
There's still a hidden issue in our code though. We'll discuss it in a moment. Can you see it now allready?
Feedback? See an issue? Feel free to mention it here.
If you want to be kept up to date, consider getting the newsletter.