List may be unbound when having a definite index

Question:
I’m trying to add something to my program where you list things you want to do and it will pick on for you. Although, it says my list may be unbound, even after trying to add something so it would have at lease one index.

Repl link:
Replit.com/@randomcat962/Pick-it-for-you

#This code is inside of a def command
  print("Please enter the things you want to do. Type END when your finished.")
  END = False

  while END == False:
    option = input()
    mono = [] #Already tried to give it an index

    if option == "END":
      END = True
    else:
      mono.append(option)

  result = random.choice(mono)
  print("This sounds good:", result)

Hi @randomcat962 !
Your code appears to work fine, but it says IndexError: list indices out of range, which doesn’t make sense.
After consulting with ChatGPT, it has provided this code:


def lmp():
  print("Please enter the things you want to do. Type END when you're finished.")
  END = False
  mono = []

  while not END:
    option = input()

    if option == "END":
      END = True
    else:
      mono.append(option)

  if mono:
    result = random.choice(mono)
    print("This sounds good:", result)
  else:
    print("You didn't enter any options.")

lmp()
1 Like

I have commented 2 arrows on a selection of your code you have shown, which together is the problem.

First of all, everything in the whole loop will run every time the while statement is True, therefore the following will happen in every loop:

  • Ask for an option
  • reset/create an empty list called mono
  • make variable END to be True if ‘END’ is entered, else add the option into list ‘mono’

Then, the problem is here

It is inside the whole loop, which means the list will be emptied out every time you enter an option.
Solution: you should place the mono = [] outside the while loop

Optimisation tips: you can use the break keyword to exit a loop, therefore you can remove the END variable, make the while statement into while True:, and change the END = True into break.
Also you can change the if option == "END": into if option.upper() == "END": , so the user can exit by entering not just END, but also exit by entering end, End, etc

3 Likes