Python Forum
Stop a function if the list it needs is empty
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stop a function if the list it needs is empty
#1
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?
Reply
#2
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.
Reply
#3
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Code with empty list not executing adeana 9 3,633 Dec-11-2023, 08:27 AM
Last Post: buran
  set.difference of two list gives empty result wardancer84 4 1,433 Jun-14-2022, 01:36 PM
Last Post: wardancer84
  Showing an empty chart, then input data via function kgall89 0 943 Jun-02-2022, 01:53 AM
Last Post: kgall89
  displaying empty list vlearner 5 1,606 Jan-19-2022, 09:12 AM
Last Post: perfringo
  Remove empty keys in a python list python_student 7 2,899 Jan-12-2022, 10:23 PM
Last Post: python_student
  Time.sleep: stop appending item to the list if time is early quest 0 1,846 Apr-13-2021, 11:44 AM
Last Post: quest
  What is the value after JOINING an empty list? JaneTan 2 5,060 Jan-04-2021, 06:25 PM
Last Post: deanhystad
  Printing empty list? hhydration 2 2,078 Oct-28-2020, 11:34 AM
Last Post: Atekka
  Need help to make an empty list with possibility to add Arnsol 1 1,771 Mar-19-2020, 06:08 PM
Last Post: michael1789
  append list to empty array SchroedingersLion 1 2,143 Feb-02-2020, 05:29 PM
Last Post: SchroedingersLion

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020