0

so currently im working on a function that checks if a user/computer has a blackjack in my black jack game however i noticed that when using an

if condition and condition

if one condition is met the entire statment is true even though that shouldnt be the case when using

and

am i doing something wrong ? here is the function:

def check_for_jack():
    #user has jack
    if 'ace' and "king" in user_deck:
        print('You have a black jack, You win')
    elif'ace' and "queen" in user_deck:
        print('You have a black jack, You win')
    elif 'ace' and "jack" in user_deck:
        print('You have a black jack, You win')
    elif 'ace' and "ten" in user_deck:
        print('You have a black jack, You win')
    #computer has jack
    elif 'ace' and "king" in computer_deck:
        print('Computer has a black jack, You lose')
    elif'ace' and "queen" in computer_deck:
        print('Computer has a black jack, You lose')
    elif 'ace' and "jack" in computer_deck:
        print('Computer has a black jack, You lose')
    elif 'ace' and "ten" in computer_deck:
        print('Computer has a black jack, You lose')

to further explain what i mean

user_deck = ['jack', 'one']

since there is only a jack nothing should happen instead i get

"You have a black jack, you win
  • 2
    ``` if 'ace' and "king" in user_deck: ``` Checks if ```king``` is in ```user_deck``` and that the string ```ace``` evaluates to ```True``` you are missing ```'ace' in user_deck``` – dosas Jun 29 '22 at 14:43

1 Answers1

1

Check for membership separately, like so:

if 'ace' in user_deck and "king" in user_deck:

Even better, shorten the code like so:

def check_for_jack():
    # User has jack:
    if ('ace' in user_deck and
        ('king' in user_deck or
         'queen' in user_deck or
         'jack' in user_deck or
         'ten' in user_deck)):
        print('You have a black jack, You win')
    # Computer has jack:
    elif ('ace' in computer_deck and
        ('king' in computer_deck or
         'queen' in computer_deck or
         'jack' in computer_deck or
         'ten' in computer_deck)):
        print('Computer has a black jack, You lose')
    # Add the pass-through condition: this one does nothing.
    # But you may want to print something to the user:
    else:
        pass

Even better, make a function to shorten the code further:

def is_jack_in_list(lst):
    return('ace' in lst and
           ('king' in lst or
            'queen' in lst or
            'jack' in lst or
            'ten' in lst))

def check_for_jack():
    if is_jack_in_list(user_deck):
        print('You have a black jack, You win')
    elif is_jack_in_list(computer_deck):
        print('Computer has a black jack, You lose')
    # Add the pass-through condition: this one does nothing.
    # But you may want to print something to the user:
    else:
        pass
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47