0

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?

Michael M.
  • 10,486
  • 9
  • 18
  • 34

5 Answers5

1

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.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
1

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'
ti7
  • 16,375
  • 6
  • 40
  • 68
0

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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

only available in the interpreter

nothing and ^C

>>> 
KeyboardInterrupt
ti7
  • 16,375
  • 6
  • 40
  • 68
0

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'
blhsing
  • 91,368
  • 6
  • 71
  • 106