Treating a string as an integer

154 views Asked by At

I'm trying to make a very simple Blackjack game. When you get dealt two cards, everything's okay if they're both integers or strings, but I get an error if the two cards dealt are a string and an integer.

How can I make it so that if you get dealt a 7 and a Queen, the Queen will be treated as 10, giving you a total of 17?

#imports
import random

Jack = 10
Queen = 10
King = 10
Ace = 1 or 11

Cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']
#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
Card1 = random.choice(Cards)
Card2 = random.choice(Cards)
Total = Card1 + Card2
print(Card1,'and a', Card2, '. Your total is', Total)






#print(int(Jack + Ace))
3

There are 3 answers

5
Padraic Cunningham On BEST ANSWER

use a dict mapping cards to values:

Cards = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
         "10": 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 10}

#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
keys = list(Cards)
Card1 = random.choice(keys)
Card2 = random.choice(keys)
Total = Cards[Card1] + Cards[Card2]
print(Card1, 'and a', Card2, '. Your total is', Total)

Or use .items:

Cards = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
         "10": 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 10}

#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
c = list(Cards.items())
Card1 = random.choice(c)
Card2 = random.choice(c)
Total = Card1[1] + Card2[1]
print(Card1[0], 'and a', Card2[0], '. Your total is', Total)
0
Namit Singal On

Use a cards mapping like this :-

import random

Jack = 10
Queen = 10
King = 10
Ace = 1 or 11

Cards_map = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 'Jack': 10, 'Queen': 11, 'King': 12, 'Ace': 13}
Cards=list(Cards_map)
#Faces = Jack, Queen, King, Ace
print('Welcome to Blackjack!\n\nHere are your cards: \n ')
Card1 = random.choice(Cards)
Card2 = random.choice(Cards)
Total = Cards_map[Card1] + Cards_map[Card2]
print(Card1,'and a', Card2, '. Your total is', Total)
0
Alexander McFarlane On

Use a dictionary as:

Cards = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:'Jack', 12:'Queen', 13:'King', 14:'Ace'}

print('Welcome to Blackjack!\n\nHere are your cards: \n ')
Card1 = random.choice(Cards.keys())
Card2 = random.choice(Cards.keys())
Total = Card1 + Card2
print(Cards[Card1],'and a', Cards[Card2], '. Your total is', Total)