0

I am fairly new to coding so please bear with me. I am using random.choice for my code to run. So, sometimes it gives me an error 'Cannot choose from an empty sequence' and sometimes it does not. Now, what I want is that, I want to have a way ( maybe an if statement) which says if 'error occurs' then rerun the whole code. So, this way I would end up not getting an error as it would rerun until I do not get an error. I am not sure if this is even possible in python.

Thanks in advance.

2
  • 3
    This site is for problems specific to the Pi, not general Python/programming questions. I suggest you work through some Python tutorials.
    – joan
    Nov 17, 2020 at 12:29
  • 2
    Search up Python exception handling... Nov 17, 2020 at 12:44

1 Answer 1

1

Without seeing the code, it is hard to give a specific answer, but I can try for a general one. (that try was a bad pun as we will see).

What you need here is a try except block. Basically, you can tell Python if it comes to an error, to do something. In this case, we will tell it to do nothing and wrap the whole thing in a while loop.

from random import choice


# Keep doing this loop until we hit break.
while True:

    # Some stuff happens here that may or may not populate your list.

    try:
        var = choice(the_list) # This is the part that has been breaking your code.
        break # If the above succeeds, we break here
    except IndexError:
        # If there is an IndexError (the type you are having), wait a second then 
        # the loop will repeat.
        sleep(1) 

# Do stuff with var.

That is your general answer based on what you asked. How I would approach this is a bit simpler and more elegant I think.

from random import choice
from time import sleep

the_list = []

while not the_list:
    # Try to get the list information
    sleep(1) # Just so we aren't doing this over and over redundantly.

var = choice(the_list)
# Do stuff with var.

Hope this helps!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.