0

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.

1
  • 1
    I know nothing about python, but putting something like i = "A B C" before the while loop should work, I guess. Commented Mar 31, 2013 at 16:35

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

First solution is simply wrong. A line is consumed and gone forever. Second one is not elegant.
@mostruash: the 2nd solution is a common Python idiom to keep from repeating yourself. If it's any consolation, the compiled code in 3.x doesn't actually test the boolean value of built-in True on each pass. In practice it's a do-while loop.
Crap. Sorry for not replying - I got sidetracked. The first solution is incorrect (I know because I already tried that.) Time to test the second one.
0
    def getBASIC():
   l = []
   x = 1
   while x == 1:
      i = input()
      l.append(i)
      if len(i.split()) != 3:
         x = 0
   return l

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.