Calculate Hand Value in a Blackjack Hand I have built a Blackjack simulator in Python. I need to decrease the execution time. I have used a profiler to identify key bottlenecks in the execution.
The following function is responsible for about 15% of the total run time.

def value(self):
    value = 0
    has_ace = False

    for card in self.cards:
        value += card.value

        if card.rank == "A":
            has_ace = True

    if has_ace and value &lt;= 11:
        value += 10

    return value


The above function is used to calculate the score of a hand.
A hand can have multiple cards.
A card has a value and a rank.

In Blackjack, an Ace can be worth 1 or 11.

Is there a better way to go?
This function doesn't have any really obvious inefficiencies, so I assume we're looking to shave off every possible clock cycle...

Sometimes it's faster to use Python's built-in aggregation functions than to use a for loop.  Here's how you could use sum and any:

def value(self) -&gt; int:
    value = sum(card.value for card in self.cards)
    if value &lt;= 11 and any(card.rank == "A" for card in self.cards):
        value += 10
    return value


Note the ordering of the and expression to make sure that the any iteration only happens if the value condition has already been met!

If you have flexibility over the representation of the cards, you might try making the rank an Enum with integer values.  I'd expect comparing two integer enums to be just a smidge faster than comparing two strings.