Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
&引用;而不是在;错误-python_Python_Loops_Variables_While Loop - Fatal编程技术网

&引用;而不是在;错误-python

&引用;而不是在;错误-python,python,loops,variables,while-loop,Python,Loops,Variables,While Loop,在本例中,我们将PH[0]设置为'tenofhearts',并将guess设置为'Ten' 列表“PH”表示玩家在围棋纸牌游戏中的手牌。当用户猜一张卡片时,他们必须猜一张与手中卡片对应的卡片。我编写了这段代码,这样,如果用户输入了无效的猜测(如果猜测不在PH中,他们将再次被提示输入新的猜测) 我觉得数组中的变量有问题,但是我不太确定 当代码被执行时,循环将永远继续。我需要能够退出循环,以便返回猜测,以便将其输入到下一个函数中 如果有人能帮我解决这个问题 guess = str(raw_input

在本例中,我们将
PH[0]
设置为
'tenofhearts'
,并将
guess
设置为
'Ten'

列表“PH”表示玩家在围棋纸牌游戏中的手牌。当用户猜一张卡片时,他们必须猜一张与手中卡片对应的卡片。我编写了这段代码,这样,如果用户输入了无效的猜测(如果猜测不在
PH
中,他们将再次被提示输入新的猜测)

我觉得数组中的变量有问题,但是我不太确定

当代码被执行时,循环将永远继续。我需要能够退出循环,以便返回猜测,以便将其输入到下一个函数中

如果有人能帮我解决这个问题

guess = str(raw_input("Make a guess : "))

guess11 = guess, 'of Hearts'
guess1 = " ".join(guess11)

guess22 = guess, 'of Diamonds'
guess2 = " ".join(guess22)

guess33 = guess, 'of Clubs'
guess3 = " ".join(guess33)

guess44 = guess, 'of Spades'
guess4 = " ".join(guess44)

while PH[0] not in [guess1, guess2, guess3, guess4] :
    print "You do not have a card like that in your hand."
    guess = str(raw_input("Make another guess : "))

    guess11 = guess, 'of Hearts'
    guess1 = " ".join(guess11)

    guess22 = guess, 'of Diamonds'
    guess2 = " ".join(guess22)

    guess33 = guess, 'of Clubs'
    guess3 = " ".join(guess33)

    guess44 = guess, 'of Spades'
    guess4 = " ".join(guess44)

return guess

你只是在测试玩家手中的第一张牌是否是他猜到的。您需要测试手中的每张卡:

while not any(guess in PH for guess in [guess1, guess2, guess3, guess4]):
这将获得每一张猜中的牌,并依次对该牌进行测试
any()
在找到匹配项时停止循环猜测

更好的方法仍然是使用集合交点:

guesses = {guess1, guess2, guess3, guess4}
while not guesses.intersection(PH):
    # ask for new guesses
您希望避免必须键入两次“询问猜测”代码;使用
while True启动循环,并在做出正确猜测后使用
break
结束循环:

suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades')

while True:
    guess = raw_input("Make a guess:")
    guesses = {'{} of {}'.format(guess, suit) for suit in suits}
    if guesses.intersection(PH):
        # correct guess!
        break
    print "You do not have a card like that in your hand."

我使用了一套理解来构建循环中的猜测。

那代码伤了我的眼睛!了解如何编写代码。这会让你的生活变得更加轻松。当我将
PH[0]
设置为
'tenofhearts'
猜测
设置为
'Ten'
时,这对我来说很有效。循环正确退出。
raw\u输入
已经是一个string@Basic我肯定会研究这一点,并学习如何使我的代码更好。我刚刚开始学习。谢谢你的邀请help@EvanCooper:但是您的
while
循环直到
PH[0]
中有匹配的卡时才会结束。其他的部分永远无法到达。好吧,现在我明白了。多谢各位