Stop code execution if a certain value is not present in a column

Question:

I want only certain values to be filled in a column (from a list A-H) and if the value is not present in that list then the code should thrown an error and stop executing further.


res = APAC['colA'].isin(['A','B','C','D','E','F','G','H'])
try:
    for i in res:
        if i == False:
            print('Different response than present in the list')
except Exception as e:
       print(e)
       raise

In short if colA contains any other values other than A,B,C,D,E,F,G,H then thrown an error and stop code from executing further.

Using the code above, I am not able to stop code execution. Help

Asked By: lfox

||

Answers:

You can raise an exception instead (or in addition) to printing it. You also don’t need to catch it

res = APAC['colA'].isin(['A','B','C','D','E','F','G','H'])
for i, val in enumerate(res):
    if not val:
        raise Exception(f'Different response than present in the list in row {i}')

Output in case of failure:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    raise Exception('Different response than present in the list')
Exception: Different response than present in the list in row 6
Answered By: Guy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.