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:

1
2
3
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
1
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:


1
2
3
4
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
  what to return for an empty list Skaperen 2 1,292 May-24-2024, 05:17 PM
Last Post: Skaperen
  Code with empty list not executing adeana 9 5,974 Dec-11-2023, 08:27 AM
Last Post: buran
  set.difference of two list gives empty result wardancer84 4 2,669 Jun-14-2022, 01:36 PM
Last Post: wardancer84
  Showing an empty chart, then input data via function kgall89 0 1,523 Jun-02-2022, 01:53 AM
Last Post: kgall89
  displaying empty list vlearner 5 3,059 Jan-19-2022, 09:12 AM
Last Post: perfringo
  Remove empty keys in a python list python_student 7 5,752 Jan-12-2022, 10:23 PM
Last Post: python_student
  Time.sleep: stop appending item to the list if time is early quest 0 2,429 Apr-13-2021, 11:44 AM
Last Post: quest
  What is the value after JOINING an empty list? JaneTan 2 7,518 Jan-04-2021, 06:25 PM
Last Post: deanhystad
  Printing empty list? hhydration 2 2,884 Oct-28-2020, 11:34 AM
Last Post: Atekka
  Need help to make an empty list with possibility to add Arnsol 1 2,483 Mar-19-2020, 06:08 PM
Last Post: michael1789

Forum Jump:

User Panel Messages

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