Why am I getting this error in python: ValueError: invalid literal for int() with base 10: '2 of Hearts'

52 Views Asked by At

I am writing a Python code for a Black Jack game, and I am getting an issue when trying to append an index of a variable to another variable. I define these variables in seperate functions, but I have set them as global in each function. This is the code snippet that is giving me the error.

def GiveCard():
    global ValuePla1 #define variables as global
    global ValuePla2
    global ValuePla3
    global ValuePla4
    global ValuePla5
    for i in playerlist: #loop to iterate over each player
        index=FinalDeck.index(random.choice(FinalDeck)) #get index of random card
        print("Player", i, "card is", FinalDeck[index]) #print random card based on index
        FinalDeck.pop(index) #delete 1the card that was printed in the line above
        card=FinalDeck[index] #save printed card to variable so that that variable can be accesed by the following if statements
        if card[0]=="A": #If selected card is ace, ask whih value the player wants it to have
            AceChoice=int(input("Do you want your ace to equal 1 or 11?"))
            if AceChoice == 1:
                card=1 #save chosen value to 'card' so that it can be appended to the player value list
            elif AceChoice==11:
                card=11
        if i == '1': #check which player/index currently on, then append only the number to the playervalue list
            ValuePla1+=int((card[0])) #append the first value of the card (the number) to the value list and make it a integer
            continue
        elif i == '2':
            ValuePla2+=int((card[0]))
            continue
        elif i == '3':
            ValuePla3+=int((card[0]))
            continue
        elif i == '4':
            ValuePla4+=int((card[0]))
            continue
        elif i == '5':
            ValuePla5+=int((card[0]))
            continue

I have tried setting the variables to global variables before initializing them, and setting specific variables to integers, to make sure that there is no issue adding a number to a variable.

1

There are 1 best solutions below

0
Debi Prasad On

This error has nothing to do with the global variable rather the conversion that you are doing, the issues lies with the conversion of the character to integer type.
i.e probably your card[0] contains the value 2 of Hearts instead of string 2, hence when you are trying to convert the whole sentence it is throwing errors.
Try replacing int((card[0])) with int((card[0][0])) or int((card[0].split()[0])) for every occurrence in the given code snippet, i think that will fix your issue.