iamtesla
iamtesla

Reputation: 423

python blackjack game, seems to be ignoring 'if' statement

I've been trying to make a simple blackjack game in python and I seem to be stuck, my code is as follows:

from random import choice

def deck():
    cards = range(1, 12)
    return choice(cards)

def diack():
    card1= deck()
    card2 = deck()
    hand = card1 + card2
    print hand
    if hand < 21:
         print raw_input("Would you like to hit or stand?")
         if "hit":
             return hand + deck()
         elif "stand": 
             return hand

When I run that it seems to work for "hit" but when I type in "stand" it seems to "hit" aswell. As you can probably tell by now I am extremely new to programming. Could you guys help point me in the right direction on how to make my game work (I'd like to use as much of my code as possible).

Upvotes: 1

Views: 477

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123830

if "hit" just tests if the string "hit" exists, and it does. Thus, the elif statement is never executed.

You need to capture the user input in a variable and test against that instead:

choice = raw_input("Would you like to hit or stand?")
print choice
if choice == "hit":
    return hand + deck()
elif choice == "stand": 
    return hand

Upvotes: 5

abarnert
abarnert

Reputation: 365945

Assuming you get the indentation right:

print raw_input("Would you like to hit or stand?")
if "hit":
    return hand + deck()
elif "stand": 
    return hand

Your if is just checking whether the string "hit" is true. All non-empty strings are true, and "hit" is non-empty, so this will always succeed.

What you want is something like this:

cmd = raw_input("Would you like to hit or stand?")
if cmd == "hit":
    return hand + deck()
elif cmd == "stand": 
    return hand

Now you're checking whether the result of raw_input is the string "hit", which is what you want.

Upvotes: 4

Related Questions