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.
Look at the documentation:
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.
So you have to pass an iterable as argument, not an int!
sum((a, b))
should work correctly.
This is a function which is intended to be used when you have many values stored in a list (for example), if you want to sum two values, you should simply use a + b
.
sum expects iterable object (like list). So the code should be:
def black_jack(a, b):
if sum([a, b]) > 21:
return 0
else:
return sum([a, b])
print black_jack(10, 5)
sum is builtin function, look at the documentation:
In [1]: sum?
Docstring:
sum(sequence[, start]) -> value
Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, return start.
Type: builtin_function_or_method
so you need to pass it a iterable! :
solution1
sum([a, b]) #list
solution2
sum((a, b)) #tuple
sum
takes first argument as a list.Here you are:
def black_jack(a, b):
if (sum([a], b) > 21):
return 0
else:
return sum([a], b)
print black_jack(10, 5)