-2
def hit():
    global hitsum
    hitsum = 0
    v=random.choice(cards)
    c=random.choice(suits)
    if v=="Ace":
        hitsum=hitsum+1
        print "You were dealt","a",v,"of",c
    elif v=="Jack":
        hitsum=hitsum+11
        print "You were dealt","a",v,"of",c
    elif v=="Queen":
        hitsum=hitsum+12
        print "You were dealt","a",v,"of",c
    elif v=="King":
        hitsum=hitsum+13
        print "You were dealt","a",v,"of",c
    else:
        hitsum=hitsum+v
        print "You were dealt","a",v,"of",c

computer()

choice=raw_input("Would you like to hit or stay? ")
if choice=="hit":
    hit()
    totalsum = hitsum + usersum
    print "Your total is", totalsum

elif choice=="stay":
    totalsum=usersum

else:
    print "Invalid request"

This code is an excerpt from my blackjack game. I made a user defined function for randomly generating a card whenever someone asks for a hit. However this only works for one choice. If i choose hit once, I don't get an option to choose it again. how do i rectify that?

1 Answers1

0
choice=raw_input("Would you like to hit or stay? ")
while choice=="hit":
    hit()
    totalsum = hitsum + usersum
    print "Your total is", totalsum
    choice=raw_input("Would you like to hit or stay? ")

I would strongly recommend changing how hit and hitsum are handled. Instead of making it global, why not return it? So at the end of hit, you would have

return hitsum

So then in the call you could do

totalsum = usersum + hit()

I see a few other issues here as well. The next time through your choice==hit loop, usersum will be back to whatever it used to be. I don't think that's what you want. Surely you want to increase usersum by hitsum. In that case, replace the totalsum = ... by

usersum += hit()

Finally, in your hit function, why define hitsum=0 at the beginning?

Joel
  • 22,598
  • 6
  • 69
  • 93
  • note - just noticed I had a bug in my initial code snippet. I just corrected it. So if you grabbed an earlier version, you want to update it. – Joel Feb 07 '15 at 10:59
  • Thanks Joel! Went through all your suggestions and it really helped me with my problems. – Dhruv Khanna Feb 08 '15 at 12:19