Sum of Integers - 'int' object is not iterable

前端 未结 5 1181
盖世英雄少女心
盖世英雄少女心 2020-11-30 14:54

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:
               


        
5条回答
  •  日久生厌
    2020-11-30 15:04

    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.

提交回复
热议问题