2

There is a difference when I use assert and raised ValuError, why?

The following code, only stop my script when I use raise ValueError, assert does not work.

assert (len(dictA) != len(dictB)), 'Your have an .... error'

if len(dictA) != len(dictB):
    raise ValueError('Your have an ... error')
martineau
  • 119,623
  • 25
  • 170
  • 301
gusa10
  • 169
  • 1
  • 1
  • 10
  • 1
    Note also that this isn't best practice usage of assert, see e.g. https://stackoverflow.com/a/945135/3001761 – jonrsharpe Jan 16 '19 at 12:16

1 Answers1

3

You need to use

assert (len(dictA) == len(dictB))

The error is thrown when the condition evaluates to False.

Filipe Aleixo
  • 3,924
  • 3
  • 41
  • 74
  • Thank you Felipe. Do you mind to explain which one (assert or valueerror) is better to use in this situation? – gusa10 Jan 16 '19 at 13:23
  • Depends on your use case. Check the accepted answer to this question https://stackoverflow.com/questions/40182944/difference-between-raise-try-and-assert/40183195 – Filipe Aleixo Jan 16 '19 at 13:47