Python problems with whole comparison

I use the function in a card game to check the value of each card and see if it is larger than the last game.

def Valid(card):
prev=pile[len(pile)-1]
cardValue=0
prevValue=0
if card[0]=="J":
    cardValue=11
elif card[0]=="Q":
    cardValue=12
elif card[0]=="K":
    cardValue=13
elif card[0]=="A":
    cardValue=14
else:
    cardValue=card[0]
prevValue=prev[0]
if cardValue>prevValue:
    return True
elif cardValue==prevValue:
    return True
else:
    return False

The problem is that whenever I receive a card, it does not seem to work. He believes that 13> 2 is true, for example

edit: sorry i meant that he thinks 13> 2 - False

+5
source share
3 answers

I think you mean what he says is true "2"> 13. You need to change

cardValue=card[0]

to

cardValue=int(card[0])
+12
source

Why not use a dictionary instead of a large cascade of if / else blocks?

cards = dict(zip((str(x) for x in range(1, 11)), range(1, 11)))
cards['J'] = 11
cards['Q'] = 12
cards['K'] = 13
cards['A'] = 14

then

cardValue = cards[card[0]]
+3
source

Using dict will make your code much cleaner:

Replace:

if card[0]=="J":
    cardValue=11
elif card[0]=="Q":
    cardValue=12
elif card[0]=="K":
    cardValue=13
elif card[0]=="A":
    cardValue=14
else:
    cardValue=card[0]

with:

cardMap = { 'J': 11, 'Q':12, 'K': 13, 'A': 14 }
cardValue = cardMap.get(card[0]) or int(card[0])
+2
source

All Articles