Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state.
Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes.
For example, if you’re writing a function to read from a configuration file into a
dict, improper formatting in the file should raise a
ConfigurationSyntaxError, while you can
assert that you’re not about to return
In your example, if
x is a value set via a user interface or from an external source, an exception is best.
x is only set by your own code in the same program, go with an assertion.