为什么这一块代码会出现错误,而另一块代码却不会?
Why does this one chunk of code come up with error but the other one doesn't?
我有两段 Python 代码 - 一段有效,另一段出现错误。这是什么规则?
这是出现错误的代码块,以及错误:
代码:
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!"
我在提示中收到此错误消息:
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 个空格(不是制表符)?我从您的第一个示例中剪切并粘贴了您的代码(从 insanity 原始输入开始),它 运行 在我的机器上运行良好。
切线关闭:
正如您已经发现的那样,尝试使用级联 if-else 子句编写任何规模的故事很快就会变得笨拙。
这是一个快速 state-machine 实现,可以轻松编写故事 room-by-room:
# 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()
并重写您的故事以使用它
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")
为了调试,我向 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)
并像 story._state_graph("test.png")
那样调用它会导致
希望您觉得它有趣且有用。
接下来要考虑的事情:
房间库存:你可以拿的东西
玩家物品栏:可以使用或掉落的东西
可选选项:只有物品栏中有红色钥匙才能打开红色门
可修改的房间:如果你进入幽静的小树林并点燃它,当你return之后
它应该是一个烧焦的小树林
我有两段 Python 代码 - 一段有效,另一段出现错误。这是什么规则?
这是出现错误的代码块,以及错误:
代码:
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!"
我在提示中收到此错误消息:
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 个空格(不是制表符)?我从您的第一个示例中剪切并粘贴了您的代码(从 insanity 原始输入开始),它 运行 在我的机器上运行良好。
切线关闭:
正如您已经发现的那样,尝试使用级联 if-else 子句编写任何规模的故事很快就会变得笨拙。
这是一个快速 state-machine 实现,可以轻松编写故事 room-by-room:
# 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()
并重写您的故事以使用它
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")
为了调试,我向 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)
并像 story._state_graph("test.png")
那样调用它会导致
希望您觉得它有趣且有用。
接下来要考虑的事情:
房间库存:你可以拿的东西
玩家物品栏:可以使用或掉落的东西
可选选项:只有物品栏中有红色钥匙才能打开红色门
可修改的房间:如果你进入幽静的小树林并点燃它,当你return之后
它应该是一个烧焦的小树林