Python拒绝更改variab

2024-04-27 02:54:15 发布

您现在位置:Python中文网/ 问答频道 /正文

Python不会在被询问时将我的变量Ace、Jack、Queen或King更改为10,相反,它似乎跳过while循环,继续执行。你知道吗

我使用的是python3.5。你知道吗

Ace = "Ace"
Jack = "Jack"
Queen = "Queen"
King = "King"

x = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace]
x1 = random.choice(x)   
x2 = random.choice(x)

# this array is irrelevant to the question.
suit = ["Spades", "Hearts", "Diamonds", "Clubs"]
suit1 = random.choice(suit)
suit2 = random.choice(suit)
while suit1 == suit2:
    suit2 = random.choice(suit)

Ace = "Ace"
Jack = "Jack"
Queen = "Queen"
King = "King"

while x1 == ["Jack", "Queen" , "King"]:
    x1 == 10

while x2 == ["Jack" , "Queen" , "King"]:
    x2 == 10

print ("Your cards are the " + str(x1) + " of " + str(suit1) + 
       " and the " + str(x2) + " of " + str(suit2))
print (str(x1) + " " + str(x2))

# When it tries to add the two variables here, it comes up with an error, 
# as it cannot add "King" to "10", since "King" is not a number.
total = (int(x1) + int(x2))

Tags: thetorandomx1x2acejacksuit
2条回答

替换:

while x1 == ["Jack", "Queen" , "King"]:
    x1 == 10

使用:

while x1 in ["Jack", "Queen" , "King"]:
    x1 = 10

第一行的问题是它没有检查x1是否在facecards列表中,而是测试x1是否真的是facecards列表。你知道吗

第二行的问题是==是一个相等测试。您只需要=,这是一个赋值。你知道吗

这段代码有各种各样的错误,但是可以把它看作是一个玩类的机会。考虑以下几点:

class Face(object):
    def __init__(self, face, value):
        self.face = face
        self.value = value
    def __int__(self):
        return self.value
    def __str__(self):
        return self.face
    def __repr__(self):
        return self.face

现在您可以制作如下卡片:

card = Face('king',13)
card #will return 'king'
str(card) #will return 'king'
int(card) #will return 13

相关问题 更多 >