Python Forum
Stop a function if the list it needs is empty - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Stop a function if the list it needs is empty (/thread-28604.html)



Stop a function if the list it needs is empty - Pedroski55 - Jul-25-2020

I have a function to take theWords, a list of words or phrases, and make an html table with them. Works OK.

Sometimes, I forget to click the button "get the words", so the words list is empty. Nothing happens, no error.

I'd like to catch that with something like:

if len(theWords) == 0:
    echoMessage('You forgot the words Dummkopf!)
    exit()
What is the best way to jump out of a function if a condition is not met?


RE: Stop a function if the list it needs is empty - Gribouillis - Jul-25-2020

Use return instead of exit().

Depending on the context, it may be preferable to raise an exception
raise RuntimeError("You forgot the words Dummkopf!")
the advantage of this is that the code that called the function can detect that an error happened and take appropriate action.


RE: Stop a function if the list it needs is empty - Pedroski55 - Jul-25-2020

Thanks!

I put this at the top of the function:


def makeTable():
        if len(theWords) == 0:
            echoMessage("You forgot the words Dummkopf!")
            return;
does the Job nicely! Thanks!