Python 为什么这一段代码出现错误,而另一段没有';T

Python 为什么这一段代码出现错误,而另一段没有';T,python,if-statement,whitespace,Python,If Statement,Whitespace,我有两段Python代码——一段有效,另一段出错。这是什么规定 以下是获得错误的代码块以及错误: 代码: 我在提示符中收到此错误消息: File "ex31.py", line 29 print "Now what will you do with the jello?" ^ IndentationError: unindent does not match any outer indentation

我有两段Python代码——一段有效,另一段出错。这是什么规定

以下是获得错误的代码块以及错误:

代码:

我在提示符中收到此错误消息:

  File "ex31.py", line 29
  print "Now what will you do with the jello?"
                                           ^
IndentationError: unindent does not match any outer indentation level
但当我的代码是这样的:

elif door == "2": 
print "You stare into the endless abyss at Cthulhu's retina."
print "1. blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."

insanity = raw_input("> ")

if insanity == "1" or insanity == "2": 
    print "Your body survives powered by a mind of jello. Good job!" 
        print "Now what will you do with the jello?"
        print "1. Eat it."
        print "2. Take it out and load it in a gun."
        print "3 Nothing."

        jello = raw_input("> ")

        if jello == "1" or jello == "2":
            print "Your mind is powered by it remember? Now you are dead!"
        elif jello == "3":
            print "Smart move. You will survive." 
        else:
            print "Do something!" 

else: 
    print "The insanity rots your eyes into a pool of muck. Good job!"
我没有收到错误消息

基本上,我的问题是-如果我缩进行,为什么没有收到错误消息

print "Now what will you do with the jello?"
…以及它下面的其余代码块

但是如果我把它和上面的行放在同一个缩进里,我会得到一个错误代码

这是否意味着if语句后的打印行总共只能是一行,不允许将其他打印行链接到该块第一个打印行上方if语句的输出


谢谢。

我怀疑你把空格和制表符混在一起了。最好只使用空格,以便视觉缩进与逻辑缩进匹配

检查源代码时,第二行有一个制表符:

    if insanity == "1" or insanity == "2": 
\t    print "Your body survives powered by a mind of jello. Good job!" 
        print "Now what will you do with the jello?"

我用
\t
标记了它,这使得混合缩进突出。

您没有在代码顶部的elif后面缩进:

elif door == "2": 
print "You stare into the endless abyss at Cthulhu's retina."
print "1. blueberries."
print "2. Yellow jacket clothespins."
print "3. Understanding revolvers yelling melodies."
您是否尝试过:

elif door == "2": 
    print "You stare into the endless abyss at Cthulhu's retina."
    print "1. blueberries."
    print "2. Yellow jacket clothespins."
    print "3. Understanding revolvers yelling melodies."

看看会发生什么?

您是否检查了缩进是否一致?是否到处都使用4个空格(不是制表符)?我剪切并粘贴了第一个示例中的代码(从疯狂原始输入开始),它在我的机器上运行良好。

在切线上关闭:

正如您已经发现的,尝试使用级联if-else子句来编写任何大小的故事很快就会变得很难处理

下面是一个快速的状态机实现,可以轻松地逐个房间编写故事:

# assumes Python 3.x:

def get_int(prompt, lo=None, hi=None):
    """
    Prompt user to enter an integer and return the value.

    If lo is specified, value must be >= lo
    If hi is specified, value must be <= hi
    """
    while True:
        try:
            val = int(input(prompt))
            if (lo is None or lo <= val) and (hi is None or val <= hi):
                return val
        except ValueError:
            pass

class State:
    def __init__(self, name, description, choices=None, results=None):
        self.name        = name
        self.description = description
        self.choices     = choices or tuple()
        self.results     = results or tuple()

    def run(self):
        # print room description
        print(self.description)

        if self.choices:
            # display options
            for i,choice in enumerate(self.choices):
                print("{}. {}".format(i+1, choice))
            # get user's response
            i = get_int("> ", 1, len(self.choices)) - 1
            # return the corresponding result
            return self.results[i]    # next state name

class StateMachine:
    def __init__(self):
        self.states = {}

    def add(self, *args):
        state = State(*args)
        self.states[state.name] = state

    def run(self, entry_state_name):
        name = entry_state_name
        while name:
            name = self.states[name].run()
为了调试,我在
StateMachine
中添加了一个方法,它使用
pydot
打印格式良好的状态图

# belongs to class StateMachine
    def _state_graph(self, png_name):
        # requires pydot and Graphviz
        from pydot import Dot, Edge, Node
        from collections import defaultdict

        # create graph
        graph = Dot()
        graph.set_node_defaults(
            fixedsize = "shape",
            width     = 0.8,
            height    = 0.8,
            shape     = "circle",
            style     = "solid"
        )

        # create nodes for known States
        for name in sorted(self.states):
            graph.add_node(Node(name))

        # add unique edges;
        ins  = defaultdict(int)
        outs = defaultdict(int)
        for name,state in self.states.items():
            # get unique transitions
            for res_name in set(state.results):
                # add each unique edge
                graph.add_edge(Edge(name, res_name))
                # keep count of in and out edges
                ins[res_name] += 1
                outs[name]    += 1

        # adjust formatting on nodes having no in or out edges
        for name in self.states:
            node = graph.get_node(name)[0]
            i = ins[name]
            o = outs.get(name, 0)
            if not (i or o):
                # stranded node, no connections
                node.set_shape("octagon")
                node.set_color("crimson")
            elif not i:
                # starting node
                node.set_shape("invtriangle")
                node.set_color("forestgreen")
            elif not o:
                # ending node
                node.set_shape("square")
                node.set_color("goldenrod4")

        # adjust formatting of undefined States
        graph.get_node("node")[0].set_style("dashed")
        for name in self.states:
            graph.get_node(name)[0].set_style("solid")

        graph.write_png(png_name)
把它叫做故事。_state_graph(“test.png”)会导致

我希望你觉得它有趣而且有用

下一步要考虑的事情:

  • 房间清单:您可以挑选的物品

  • 玩家清单:你可以使用或丢弃的物品

  • 可选选项:如果库存中有红色钥匙,则只能解锁红色门

  • 可修改房间:如果你进入隐蔽的小树林并放火,当你稍后返回时,它应该是一个烧焦的小树林


不,我不认为我混合了空格和制表符。当我将打印行缩进有问题的-=下以及它下面的所有内容时,没有收到错误消息。因此,Python中可能有一条规则,if语句下面只有一个函数行可以作为该语句结果的条件?我想这一定是某种我不知道的规则。OP在打印中有嵌套打印statement@PadraicCunningham他实际上没有嵌套
打印
语句。看起来他是因为标签和空格的混合。所有这些行的逻辑缩进大概都是相同的(否则它显然会像你说的那样断裂)。@PadraicCunningham再次读了一遍——他在问为什么嵌套缩进没有给出错误!正如你提到的,我在代码下做了elif——我只是没有将它准确地粘贴到堆栈溢出中。现在我将编辑它以更正它。好的,我已经编辑了代码以反映我第一次做的事情。现在是100%。您将看到,一旦我在if语句后的第一行“print”之后立即向“print”行添加另一个4空间缩进,我就不会得到任何错误。我想知道为什么这个isIf你的代码看起来像这样,这两个例子都会在第二行引起语法错误。因为情况显然不是这样,所以你应该仔细检查你的代码,编辑你的帖子,这样你所发布的内容才能与你的实际代码完全匹配。特别是当你问语法问题时,注意细节是最重要的。我想你的实际问题是,正如约翰·库格曼在他的回答中所建议的那样,你在混合制表符和空格。我尝试过使用搜索和替换进行检查,但可能我做得不好。关于如何做的任何提示,或者我只需手动将每个输入的选项卡替换为4个空格?取决于您使用的编码,您是否使用VIM、记事本等。我建议(Aptana自动将选项卡转换为4个空格)。
story = StateMachine()

story.add(
    "doors",
    "You are standing in a stuffy room with 3 doors.",
    ("door 1", "door 2",  "door 3"  ),
    ("wolves", "cthulhu", "treasury")
)

story.add(
    "cthulhu",
    "You stare into the endless abyss at Cthulhu's retina.",
    ("blueberries", "yellow jacket clothespins", "understanding revolvers yelling melodies"),
    ("jello",       "jello",                     "muck")
)

story.add(
    "muck",
    "The insanity rots your eyes into a pool of muck. Good job!"
)

story.add(
    "jello",
    "Your body survives, powered by a mind of jello. Good job!\nNow, what will you do with the jello?",
    ("eat it",   "load it into your gun", "nothing"),
    ("no_brain", "no_brain",              "survive")
)

story.add(
    "no_brain",
    "With no brain, your body shuts down; you stop breathing and are soon dead."
)

story.add(
    "survive",
    "Smart move, droolio!"
)

if __name__ == "__main__":
    story.run("doors")
# belongs to class StateMachine
    def _state_graph(self, png_name):
        # requires pydot and Graphviz
        from pydot import Dot, Edge, Node
        from collections import defaultdict

        # create graph
        graph = Dot()
        graph.set_node_defaults(
            fixedsize = "shape",
            width     = 0.8,
            height    = 0.8,
            shape     = "circle",
            style     = "solid"
        )

        # create nodes for known States
        for name in sorted(self.states):
            graph.add_node(Node(name))

        # add unique edges;
        ins  = defaultdict(int)
        outs = defaultdict(int)
        for name,state in self.states.items():
            # get unique transitions
            for res_name in set(state.results):
                # add each unique edge
                graph.add_edge(Edge(name, res_name))
                # keep count of in and out edges
                ins[res_name] += 1
                outs[name]    += 1

        # adjust formatting on nodes having no in or out edges
        for name in self.states:
            node = graph.get_node(name)[0]
            i = ins[name]
            o = outs.get(name, 0)
            if not (i or o):
                # stranded node, no connections
                node.set_shape("octagon")
                node.set_color("crimson")
            elif not i:
                # starting node
                node.set_shape("invtriangle")
                node.set_color("forestgreen")
            elif not o:
                # ending node
                node.set_shape("square")
                node.set_color("goldenrod4")

        # adjust formatting of undefined States
        graph.get_node("node")[0].set_style("dashed")
        for name in self.states:
            graph.get_node(name)[0].set_style("solid")

        graph.write_png(png_name)