Reputation: 3
I'm trying to get the value of the cards dealt to a user. Can anyone give me a hand with what I can do? Thanks
import random
from random import shuffle
# Define the deck
def deck1():
hand = []
deck = {"Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8,
"Nine": 9, "Ten": 10, "Jack": 11, "Queen": 12, "King": 13, "Ace": 14}
keys = list(deck.keys())
random.shuffle(keys)
shuffled = keys.pop()
hand.append(shuffled)
return hand
Create the user hand
userhand = []
for i in range(2):
userhand.append(deck1())
print(userhand)
# Get the sum of the user hand
print(sum(userhand))
Upvotes: 0
Views: 94
Reputation: 142651
First you need dect = {...}
outside function because it is needed to sum cards
I assume userhand
keeps two players
for player in userhand:
print(sum(deck[cardname] for cardname in player))
or longer but simpler for beginner
for player in userhand:
result = 0
for cardname in player:
result += deck[cardname]
print(result)
If userhand
keep only one player then you can nested sum()
print( sum(sum(deck[cardname] for cardname in hand) for hand in userhand) )
or longer but simpler for beginner
total_result = 0
for hand in userhand:
result = 0
for cardname in hand:
result += deck[cardname]
total_result += result
print(total_result)
Or you could use return shuffled
in deck1()
because it returns only one card and there is no need to return it as list. It will create simpler data in userhand
and it will need simpler code to sum it.
Minimal working code
import random
from random import shuffle
deck = {"Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8,
"Nine": 9, "Ten": 10, "Jack": 11, "Queen": 12, "King": 13, "Ace": 14}
# Define the deck
def deck1():
hand = []
keys = list(deck.keys())
random.shuffle(keys)
shuffled = keys.pop()
hand.append(shuffled)
return hand
userhand = []
for i in range(2):
userhand.append(deck1())
print(userhand)
# Get the sum of the user hand
for player in userhand:
print(sum(deck[cardname] for cardname in player))
for player in userhand:
result = 0
for cardname in player:
result += deck[cardname]
print(result)
print( sum(sum(deck[cardname] for cardname in hand) for hand in userhand) )
total_result = 0
for hand in userhand:
result = 0
for cardname in hand:
result += deck[cardname]
total_result += result
print(total_result)
Upvotes: 3