为什么我在 python 中收到此错误:ValueError: invalidliteral for int() with base 10: '2 of Hearts'

问题描述 投票:0回答:1

我正在为 Black Jack 游戏编写 Python 代码,在尝试将一个变量的索引附加到另一个变量时遇到问题。我在单独的函数中定义这些变量,但在每个函数中将它们设置为全局变量。这是给我错误的代码片段。

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

我尝试在初始化变量之前将其设置为全局变量,并将特定变量设置为整数,以确保向变量添加数字不会出现问题。

python blackjack
1个回答
0
投票

此错误与全局变量无关,而是与您正在进行的转换无关,问题在于字符到整数类型的转换。
即,您的

card[0]
可能包含值
2 of Hearts
而不是字符串
2
,因此,当您尝试转换整个句子时,它会抛出错误。
尝试将给定代码片段中每次出现的
int((card[0]))
替换为
int((card[0][0]))
int((card[0].split()[0]))
,我认为这会解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.