【发布时间】:2017-01-28 20:55:00
【问题描述】:
我正在使用 python 来尝试模拟 Inform 7 (inform7.com) 的基本功能。当我尝试设置房间时打印出其中的所有对象,并且房间中没有任何对象,它仍然会打印出In this room there is a。代码的相关部分在这里。
def __repr__(self):
if self.room_firstrun:
for i in things:
if things[i] == self.name:
self.objects_in_room.append(i)
self.room_firstrun = False
fullstring = 'In this room, there is a '
for i in self.objects_in_room:
if not self.objects_in_room:
fullstring = ''
break
elif i == self.objects_in_room[len(self.objects_in_room) - 1] and len(self.objects_in_room) > 2:
stringtoappend = ', and a ' + i + '.'
elif i == self.objects_in_room[len(self.objects_in_room) - 1] and len(self.objects_in_room) == 2:
stringtoappend = ' and a ' + i + '.'
elif i == self.objects_in_room[len(self.objects_in_room) - 1] and len(self.objects_in_room) == 1:
stringtoappend = i + '.'
elif i == self.objects_in_room[0]:
stringtoappend = i
else:
stringtoappend = ', a ' + i
fullstring += stringtoappend
stringtoappend = ''
return '\n----------' + self.name + '----------\n\n' + self.desc + '\n\n' + fullstring
。 if not self.objects_in_room: fullstring = '' break 行永远不会到达,即使我通过删除所有项目来验证列表是空的。我一直在尝试修复它一段时间,但它一直没有工作。也很烦人,当我在一个房间里有两件物品时,它不会显示第一个。也许我应该把它放在另一个问题中。提前感谢您的回答!
【问题讨论】:
-
将该语句移出循环。如果列表为空,则循环根本不会运行。其次,为什么要使用 stringtoappend 而不是将它们添加到完整字符串中
-
嗯....我试过了,但是没用。
-
哦,没关系,我不小心删除了它facepalm
标签: python if-statement python-3.6