-2

-Hello! So after the user enters strings, ['abc', 'def', 'ghi'] in this case, and I am trying to have the output of my function look like:

['abc', 'def', 'ghi]
1 abc
2 def
3 ghi

-This is my function:

import read_lines

lines = []

print(lines)

ci = 0

contin = True

while contin:

    if len(lines) <= ci:

            contin = False

    else:

            line = lines[ci]

            ci += 1

            print(ci, line)

-However, the output only shows:

['abc', 'def', 'ghi']  
[]  

-Side Note: I have to use a while loop for my homework assignment.

Panda1234
  • 3
  • 3

1 Answers1

1

You need a <= sign after the if len(lines) < ci':. I'm not sure if it was a typo to have two less than signs or not. As your program runs through, it adds one to ci. Eventually, ci = 4 because of the += 1 (as I'm sure you know), but since the computer does not recognize 3 as being less than 3, it continues on to the else statement, thus showing that the index is out of range, because there is no index of 4 in your list, only 0, 1, and 2.

EDIT

else:
    line = lines[ci]
    ci += 1
    print(ci, line)    
  • Thank you so much! That definitely go the error message out of the way. However, now it prints the list but doesn't print(ci, line) at all. Any suggestions? – Panda1234 Apr 15 '17 at 15:37
  • @Panda1234 make sure you still have the `print(ci, line)` at the end of the `else` statement. I'll post the code in the `else` statement that I have –  Apr 15 '17 at 15:43
  • Ok so I updated it with yours just to make sure it was correct. The output prints the list first but then just prints [ ] on the line afterwards – Panda1234 Apr 15 '17 at 15:47
  • @Panda1234 Can you update your question to show the exact code that you're writing? –  Apr 15 '17 at 15:50
  • Ok I updated it - and finally got the formatting right on here :-) – Panda1234 Apr 15 '17 at 16:18
  • @Panda1234 Sounds good! If this worked for you, could you please mark it as the accepted answer by clicking the check mark next to my answer? Thanks! –  Apr 15 '17 at 16:31
  • Okie dokie I marked your answer! If you have a moment would you help me figure out why the output doesn't print(ci, line) please? If not, thank you so much for all of your help. : – Panda1234 Apr 15 '17 at 16:35
  • @Panda1234 , I get the following output `['abc', 'def', 'ghi']` `1 abc` `2 def` `ghi` –  Apr 15 '17 at 16:48
  • Not sure why mine is different then, I even tried starting a new file and copying and pasting what is on here and I've still been getting the same output. I'll play around with it and see what happens. Thank you so so much for everything. You are a magical human being and have a great day!! :) – Panda1234 Apr 15 '17 at 18:10
  • @Panda1234 try putting the `'abc', 'def', 'ghi'` into the `lines` list. This may be your problem, as in your original question, this list is blank –  Apr 15 '17 at 18:25