变量不会在Python中分配给输入

时间:2015-02-13 20:00:14

标签: python python-3.x

我对编程很陌生,我正在阅读这本书#34;使用Python创建自己的计算机游戏"。为了测试我已经理解了这些章节,我尝试重做章节一直在做的任何游戏,并添加装饰而不参考文本寻求帮助。我已经对这部分内容进行了不同的编程,但我不明白为什么它不起作用。

def chooseletter():
    loop = True
    playerletter = ""
    computerletter = ""
    while playerletter not in "X O".split():
        playerletter = input("What letter would you like to be? X or O? \n").upper
        if playerletter == ("X"):
            computerletter = "O"
        elif playerletter == ("O"):
            computerletter = "X"
        else:
            loop = True
    return [playerletter, computerletter]

出于某种原因,无论我输入什么,此代码都会继续循环和循环。当我打开调试器时,表示甚至没有将任何内容分配给变量" playercharacter"。

我打赌这是非常明显的事情,当有人指出解决方案时,我会嘲笑自己。谢谢你的帮助。

1 个答案:

答案 0 :(得分:4)

您在.upper()方法调用中缺少括号。

playerletter = input("What letter would you like to be? X or O? \n").upper

应该阅读

playerletter = input("What letter would you like to be? X or O? \n").upper()

以下代码

playerletter = input("What letter would you like to be? X or O? \n").upper

将返回的字符串的方法对象分配给playerletter变量。如果您在该行之后print播放,您将获得:

<built-in method upper of str object at 0x7fa45670e508>

现在,由于python是动态类型的,因此将此值与'X''O'进行比较是完全有效的。由于它既不匹配,所以运行else:子句,并且满足条件playerletter not in "X O".split():,因为['X', ' ', 'O']当然不包含<built-in method upper of str object at 0x7fa45670e508>,因此while循环无限重复。


以下是您在惯用Python中的代码:

def chooseletter():
    playerletter = ''

    # use a tuple of letters in condition instead of splitting
    while playerletter not in ('X', 'O'):
        playerletter = input("What letter would you like to be? X or O? \n").upper()

    # move the setting of computerletter outside the loop
    # use the X if Z else Y construction for simplicity
    computerletter = 'O' if playerletter == 'X' else 'X'

    # instead of returning 2 values in a list, return a tuple
    return playerletter, computerletter