I'm just starting to learn python and my first project is a text based Blackjack game.
pHand being the players hand and pTotal being the total of the players cards.
The for loop seems to be exiting after the first iteration. When I print pTotal and pHand out after the loop, it shows only the first card's value every time.
Code:
import random
f = open('Documents/Python/cards.txt', 'r')
deck = f.read().splitlines()
f.close
pTotal = 0
cTotal = 0
random.shuffle(deck)
pHand = [deck[0], deck[1]]
cHand = [deck[2]]
for x in pHand:
if deck[x][0] == '1' or deck[x][0] == 'J' or deck[x][0] == 'Q' or deck[x][0] == 'K':
pTotal += 10
elif deck[x][0] == 'A':
pTotal += 11
else:
pTotal += int(deck[x][0])
Any help would be appreciated!
I think what you would want is
#using x as a list item
for x in pHand:
if x[0] == '1' or x[0] == 'J' or x[0] == 'Q' or x[0] == 'K':
pTotal += 10
elif x[0] == 'A':
pTotal += 11
else:
pTotal += int(x[0])
The for-in loop iterates through the items in pHand
using x
as a temporary variable for each value. In your case, in the first iteration, you have x = deck[0]
. In the second iteration you have x = deck[1]
.
In the code you posted, you were trying to use x
as an index, which is fine, so long as you use the right values for your loop.
#using x as an index
for x in range(0, len(pHand)):
if deck[x][0] == '1' or deck[x][0] == 'J' or deck[x][0] == 'Q' or deck[x][0] == 'K':
pTotal += 10
elif deck[x][0] == 'A':
pTotal += 11
else:
pTotal += int(deck[x][0])