... pytest.

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 new test_blackjack.py file looks like this;

from blackjack import card_score

def test_simple_usecase1():
    card_score("JK") == 20

def test_simple_usecase2():
    card_score("JKQ") == 0

def test_simple_usecase3():
    card_score("KA") == 21

def test_simple_usecase4():
    card_score("AA") == 12

And the fixed function looks like this;

def card_score(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

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.