-4

如果满足条件,我希望 if 语句中断,因为目前如果它没有提前中断,那么我的代码会出现一些意外。

问题是,我不确定在哪里休息。当我把它放在此处显示的位置时,我得到“意外缩进”,但是当我把它放回一个级别时,我得到一个错误,else 语句说“无效语法”。

编辑:如果缩进。它只是没有出现在站点代码块中。我会尝试在网站上修复它。

@duck,你认为我想做什么?我正在上 Python 课程的第一周。我来这里是为了帮助自己,而不是让我的代码被你控制。如果你能帮助我,那么我将不胜感激,否则我不需要你告诉我“学习如何编码”,而这正是我想要做的。

所以我不确定该怎么做。任何帮助,将不胜感激。

def pTurn(CampLoc, AICampLoc, score, yourHits, cHits):
    if yourHits < 5:
        hGuess = int(raw_input("Enter a co-ordinate to air-strike: "))
        print "Air-striking co-ordinate: %d" % hGuess
        for cSpot in AICampLoc:
            if hGuess == cSpot:
                yConfirMsg = "Kill confirmed!!"
                yourHits += 1
                score += 100
                AICampLoc.remove(hGuess)
            break
            else:
                yConfirMsg= "No casualties"
4

2 回答 2

1

正如其他答案所述,您缺少缩进​​,而且您有一堆不需要的代码。您的代码可以简化为:

def pTurn(CampLoc, AICampLoc, score, yourHits, cHits):
    if yourHits < 5:
        hGuess = int(raw_input("Enter a co-ordinate to air-strike: "))
        print "Air-striking co-ordinate: %d" % hGuess
        yConfirMsg= "No casualties"
        for cSpot in AICampLoc:
            if hGuess == cSpot:
                yConfirMsg = "Kill confirmed!!"
                yourHits += 1
                score += 100
                AICampLoc.remove(hGuess)
                break        
于 2013-09-26T05:06:24.523 回答
0

尝试这个:

def pTurn(CampLoc, AICampLoc, score, yourHits, cHits):
    if yourHits < 5:
    #^This line ident is probably the offending line. ;)
        hGuess = int(raw_input("Enter a co-ordinate to air-strike: "))
        print "Air-striking co-ordinate: %d" % hGuess
        for cSpot in AICampLoc:
            if hGuess == cSpot:
                yConfirMsg = "Kill confirmed!!"
                yourHits += 1
                score += 100
                AICampLoc.remove(hGuess)
                break
            else:
                yConfirMsg= "No casualties"
                score = score #You may want to fix this, since the logic doesn't make sense
                yourHits = yourHits #Fix this line as well. This is variable value assignment to the same variable.

如果这不起作用,要考虑的另一件事是,当您缩进代码的前导空格时,您可能无意中混合了制表符和空格。如果是这样,请将所有制表符转换为空格。

并且,关于引用的注释。也许您打算返回这些值?如果是这样,您需要修复这些逻辑错误。

更新:

如果您只需要中断一次仅一次,那么您应该将 break 替换为return

如果没有,那么您应该捕获该位置,继续循环执行,并使用该信息执行您必须做的任何事情。

    #...
    values = {}
    all_values = []

    for cSpot in AICampLoc:
        if hGuess == cSpot:
            yConfirMsg = "Kill confirmed!!"
            yourHits += 1
            score += 100
            AICampLoc.remove(hGuess)

            values['message'] = yConfirMsg
            values['hits'] = yourHits
            values['score'] = score
            values['camploc'] = AICampLoc

            all_values.append(values)

        else:
            yConfirMsg= "No casualties"
            #...
于 2013-09-26T05:02:38.023 回答