如果我有一个空列表,则不打印字符串

时间:2013-05-21 21:01:19

标签: python list printing

所以我有一些代码,我在开始时创建一个列表,然后询问用户是否要创建一个对象(乌龟),在这种情况下,它会将其添加到列表中,或者如果他想移动乌龟(X)。如果用户尚未创建对象,我希望它打印“需要创建对象”。但它似乎不是印刷品。我知道代码会自己打印出来,所以我想知道为什么这个函数不能正常工作。所以基本上我只想让代码打印出“如果我有一个空列表就需要创建对象”。

adventurousch = []

def RoamingTurtles(): 
   command = raw_input("---> ")
   if command == 'A':
     newAdventureTurtle()
     RoamingTurtles() 
  if command == 'X':
    if adventurousch == []:
      print "Need to create object"
    else:
      for i in adventurousch:
        i.drawSquare()
        print "test2

2 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

...
if not adventurousch:
      print "Need to create object"
...

另请参阅:Best way to check if a list is empty

答案 1 :(得分:2)

代码adventurousch == []正在测试adventurousch是否等于特定的空列表,而不是它是空的。要检查adventurousch是否为空,请使用if not adventurousch: