Dan
Dan

Reputation: 57

Returning a list of strings from input

I'm currently working on a function called, getBASIC(). This is why I'm making this:

Write a function getBASIC() which takes no arguments, and does the following: it should keep reading lines from input using a while loop; when it reaches the end it should return the whole program in the form of a list of strings.

The program takes input in the form of:

X GOTO Y  
Y GOTO Z  
Z END 

And so on and so forth.

My code for this is as follows:

def getBASIC():
   l = []
   while len(i.split()) == 3:
      i = input()
      l.append(i)
   return(l)

Problem is, I get an UnboundLocalError: local variable 'i' referenced before assignment. Now I do know why this is, but I've suddenly become an idiot and can't figure out how to fix it. Help debugging this would be appreciated. Thanks.

Upvotes: 0

Views: 373

Answers (2)

Dan
Dan

Reputation: 57

    def getBASIC():
   l = []
   x = 1
   while x == 1:
      i = input()
      l.append(i)
      if len(i.split()) != 3:
         x = 0
   return l

Upvotes: 0

Benjamin
Benjamin

Reputation: 609

Simple solution

   i = input()
   l.append(i)
   while len(i.split()) == 3:
       i = input()
       l.append(i)

other solution:

    while True:
        i = input()
        l.append(i)
        if len(i.split()) != 3:
            break

Upvotes: 3

Related Questions