-1

I have the following code. It is basically a balckjack function. It should return the sum of 3 numbers is less then 21. If bigger and it has 11 as one of the numbers it should deduct 10 from it. If after the deduction the sum is still bigger han 21 it should return 'BUST'. In the training José solved the last part with making in the elif the sum smaller or equal to 31, which of course is a nice way to have then just 'BUST' in an else and not nested into the elif. However I want to do de excercise my way with nesting the 'BUST' into the elif. So far no luck, I am guessing, because of the return I cannot put any condition afterwards.

Do you guys have any solution to make the 'BUST' a sub-condition of the elif? Here is my code, which does not work.

def blackjack(a,b,c):
    added = sum([a,b,c])
    if added <= 21:
        return added
    elif added > 21 and 11 in [a,b,c]:
        return added -10
        busted = added -10
        if busted > 21:
            return 'BUST'

It should give the following if called:

    blackjack(5,6,7) --> 18
    blackjack(9,9,9) --> 'BUST'
    blackjack(9,9,11) --> 19

2 Answers2

0
def blackjack(a,b,c):
    added = sum([a,b,c])
    if added <= 21:
        return added
    elif added > 21 and 11 in [a,b,c]:
        busted = added -10 
        if busted > 21:
            return 'BUST'
        return busted

If busted > 21 is true it return 'BUST', if not it moves on to next statement and returns busted. I dont exactly understand why you would need another method but if you want to return two different things based on a condition. if/elif or if/else block are a must.

Suven Pandey
  • 712
  • 4
  • 17
0

You can use a ternary expression on your return:

def blackjack(a,b,c):
        added = sum([a,b,c])
        if added <= 21:
            return added
        elif added > 21 and 11 in [a,b,c]:
            return (added-10) if (added-10 <= 21) else "BUST-11"

        return "BUST"

print( blackjack(5,6,7)  )
print( blackjack(9,9,9)  )
print( blackjack(9,9,11)  )
print( blackjack(10,11,11)  )

Output:

18
BUST
19
BUST-11

See Does Python have a ternary conditional operator?

You will still need the fall-trough "BUST" (for >21 w/o 11 in it) anyway - so the else solution is cleaner.

Alec
  • 6,521
  • 7
  • 23
  • 48
Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
  • Thank you Patrick, your soluiton is interesting, but de to BUST-11 not clean enough. I guess this is not cleanly doable with nesting. – StingerWolf Mar 30 '19 at 17:21
  • @StingerWolf - I just renamed it so you can see which BUST comes from where :) – Patrick Artner Mar 30 '19 at 17:22
  • Oh, you are right, my bad, in the end it gives 'BUST' if it gets renamed, so yes, I see now, thank you for your help, it is really nice to have sometimes a different perspective.:) – StingerWolf Mar 30 '19 at 17:26