Home > Back-end >  Shortest code to create an error that isn't a NameError or SyntaxError
Shortest code to create an error that isn't a NameError or SyntaxError

Time:11-07

In Python, many statements can cause errors, but I would like to know what are the simplest statements that can cause an Error except for NameError and SyntaxError and their subclasses such as IdentationError

Using the interactive Python shell, I have tried using single characters in statements but they are all NameErrors or SyntaxErrors, and I tried two characters, it is also the same, so I wonder if there are any possibilities to cause other types of errors by using 3 or fewer characters in Python. if this is impossible, then why so?

CodePudding user response:

I think the shortest one would be a three-character ZeroDivisionError. Like this:

1/0

Almost everything that isn't a NameError or SyntaxError is going to need some kind of operator, which will bump you up to three characters.

CodePudding user response:

bitwise negation of a float raises TypeError in 3 characters

>>> ~.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary ~: 'float'

CodePudding user response:

Your question is unclear if you are looking for the absolute shortest code to cause an error, or if you are looking for several short examples that cause a variety of different errors.

For the later, add these two to your list:

x, = 5 # TypeError

and

x, y = 5, # ValueError

and

x, = [] # ValueError

Not quite as short as Michael M's answer, but still short.

CodePudding user response:

only available in the interpreter

nothing and ^C

>>> 
KeyboardInterrupt

CodePudding user response:

You can cause a TypeError by trying to negate a tuple, for example:

>>> -()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: 'tuple'
  • Related