我有两段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语句的输出?
感谢。
答案 0 :(得分:3)
我怀疑你正在混合空格和制表符。最好只使用空格,以便您的视觉缩进与逻辑缩进相匹配。
检查您的源代码,第二行中有一个制表符:
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
对其进行了标记,这使得混合缩进更加突出。
答案 1 :(得分:1)
您在此代码顶部的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."
看看会发生什么?
答案 2 :(得分:1)
您是否检查过您的缩进是否一致?你到处使用4个空格(不是制表符)吗?我从第一个例子中剪切并粘贴你的代码(从精神错乱的原始输入开始),它在我的机器上运行正常。
答案 3 :(得分:1)
关闭切线:
正如你已经发现的那样,尝试用级联的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()
并重写你的故事以使用它
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")
会导致
我希望你觉得它有趣且有用。
下一步要考虑的事情:
房间库存:你可以拿起的东西
玩家库存:您可以使用或放弃的东西
可选选项:如果您的库存中有红色键,则只能解锁红门
可修改的房间:如果您进入幽静的小树林并将其点燃,当您稍后返回时,它应该是一个烧焦的小树林