My question is related to the sum function in python.
So my code is
def black_jack(a, b):
if sum(a, b) > 21:
return 0
else:
What's wrong with just the following?
def black_jack(a, b):
if a + b > 21:
return 0
else:
return a + b
print black_jack(10, 5)
In Blackjack, one can have much more than just two cards, but with your example, it appears that you assume that a hand can have only two cards. If you allow for a variable number of cards, then you'd need to use an iterable object as others have suggested:
def black_jack(values):
total = sum(values)
return 0 if total > 21 else total
print black_jack(10, 5)
From the documentation for sum():
sum(iterable[,start])Sums start and the items of an iterable from left to right and returns the total. start defaults to
0. The iterable's items are normally numbers, and the start value is not allowed to be a string.For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling
''.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().New in version 2.3.