0

So I have some code where I create a list at the start and then ask a user if he wants to make an object (turtle), in which case it adds that to the list, OR if he wants to move the turtle (X). If the user has not created the object I want it to print 'Need to create object'. But it doesn't seem to be printing. I know the code prints it out on its own so I am wondering why this isn't working within the function. So essentially I just want the code to print "Need to create object' if I have an empty list.

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
Danrex
  • 1,657
  • 4
  • 31
  • 44

2 Answers2

3

This should do the trick:

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

See also: Best way to check if a list is empty

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • That worked. My problem now is when I try to feedback into the function by entering RoamingTurtles() after the print it stops printing? – Danrex May 21 '13 at 21:18
2

The code adventurousch == [] is testing if adventurousch is equal to that specific empty list, not that it is empty. To check if adventurousch is empty, use if not adventurousch:.

Simon
  • 10,679
  • 1
  • 30
  • 44
  • So that works but when I try to get it to feed back into the function by adding RoamingTurtles() after the print it doesn't print and just goes goes through the function? – Danrex May 21 '13 at 21:16
  • 1
    Without seeing the rest of your code, it is hard to tell, but I'd be surprised if recursively calling `RoamingTurtles()` will achieve what you hope to achieve. As an alternative, I'd suggest using a loop within `RoamingTurtles()` to allow the user to create as many turtles as he/she wants. Also, using a global variable like `adventurousch` to which `newAdventureTurtle()` presumably appends a turtle makes it difficult to understand the program. I'd suggest returning the the new turtle from the function so that you can say something like `adventurousch.append(newAdventureTurtle())`. – Simon May 21 '13 at 21:32