Commonwealth Exceptions in Python

Commonwealth Exceptions in Python can be understood by following some simple functions. Learn more about this type of parameter here.

Here in Stack Overflow we often see duplicates talking about the same errors: “ImportError: No module named ‘??????’, SyntaxError: invalid syntax or NameError: name ‘???’ is not defined. This is an effort to reduce them and to have some documentation to link to.

Commonwealth Exceptions in Python: Other Errors

AssertError

The assert statement exists in almost every programming language. When you do:

assert condition

or:

assert condition, message

It’s equivalent to this:

if debug:
if not condition: raise AssertionError(message)

Assertions can include an optional message, and you can disable them when you’re done debugging.

Note: the built-in variable debug is True under normal circumstances, False when optimization is requested (command line option -O). Assignments to debug are illegal. The value for the built-in variable is determined when the interpreter starts.

KeyboardInterrupt

Error raised when the user presses the interrupt key, normally Ctrl + C or del .

ZeroDivisionError

You tried to calculate 1/0 which is undefined. See this example to find the divisors of a number:

Python 2.x Version ≥ 2.0 Version ≤ 2.7

div = float(raw_input("Divisors of: "))
for x in xrange(div+1): #includes the number itself and zero if div/x == div//x:
print x, "is a divisor of", div

Python 3.x Version ≥ 3.0

div = int(input("Divisors of: "))
for x in range(div+1): #includes the number itself and zero if div/x == div//x:
print(x, "is a divisor of", div)

It raises ZeroDivisionError because the for loop assigns that value to x. Instead it should be:

Python 2.x Version ≥ 2.0 Version ≤ 2.7

div = float(raw_input("Divisors of: "))
for x in xrange(1,div+1): #includes the number itself but not zero if div/x == div//x:

print x, “is a divisor of”, div

Python 3.x Version ≥ 3.0

div = int(input("Divisors of: "))
for x in range(1,div+1): #includes the number itself but not zero if div/x == div//x:
print(x, "is a divisor of", div)

Commonwealth Exceptions in Python: NameError: name ‘???’ is not defined

Is raised when you tried to use a variable, method or function that is not initialized (at least not before). In other words, it is raised when a requested local or global name is not found. It’s possible that you misspelt the name of the object or forgot to import something. Also maybe it’s in another scope. We’ll cover those with separate examples.

It’s simply not defined nowhere in the code

It’s possible that you forgot to initialize it, especially if it is a constant

foo # This variable is not defined
bar() # This function is not defined

Maybe it’s defined later:

baz()
def baz():
pass

Or it wasn’t imported:

needs import math

def sqrt():
x = float(input("Value: "))
return math.sqrt(x)

Python scopes and the LEGB Rule:

The so-called LEGB Rule talks about the Python scopes. Its name is based on the different scopes, ordered by the correspondent priorities:

Local → Enclosed → Global → Built-in.

Local: Variables not declared global or assigned in a function.

Enclosing: Variables defined in a function that is wrapped inside another function.

Global: Variables declared global, or assigned at the top-level of a file.

Built-in: Variables preassigned in the built-in names module.

As an example:

for i in range(4):
d = i * 2
print(d)

d is accessible because the for loop does not mark a new scope, but if it did, we would have an error and its behavior would be similar to:

def noaccess():
for i in range(4):
d = i * 2
noaccess()
print(d)

Python says NameError: name ‘d’ is not defined

Commonwealth Exceptions in Python: TypeErrors

These exceptions are caused when the type of some object should be different

TypeError: [definition/method] takes ? positional arguments but ? was given

A function or method was called with more (or less) arguments than the ones it can accept.

Example

If more arguments are given:

def foo(a): return a
foo(a,b,c,d) #And a,b,c,d are defined

If less arguments are given:

def foo(a,b,c,d): return a += b + c + d
foo(a) #And a is defined

Note: if you want use an unknown number of arguments, you can use *args or **kwargs. See *args and **kwargs

TypeError: unsupported operand type(s) for [operand]: ‘???’ and ‘???’

Some types cannot be operated together, depending on the operand.

Example

For example: + is used to concatenate and add, but you can’t use any of them for both types. For instance, trying to make a set by concatenating (+ing) ‘set1’ and ‘tuple1’ gives the error. Code:

set1, tuple1 = {1,2}, (3,4)
a = set1 + tuple1

Some types (eg: int and string) use both + but for different things:

b = 400 + 'foo'

Or they may not be even used for anything:

c = ["a","b"] - [1,2]

But you can for example add a float to an int:

d = 1 + 1.0

TypeError: ‘???’ object is not iterable/subscriptable:

For an object to be iterable it can take sequential indexes starting from zero until the indexes are no longer valid and a IndexError is raised (More technically: it has to have an iter method which returns an iterator, or which defines a getitem method that does what was previously mentioned).

Example

Here we are saying that bar is the zeroth item of 1. Nonsense:

foo = 1
bar = foo[0]

This is a more discrete version: In this example for tries to set x to amount[0], the first item in an iterable but it can’t because amount is an int:

amount = 10
for x in amount: print(x)

TypeError: ‘???’ object is not callable

You are defining a variable and calling it later (like what you do with a function or method)

Example

foo = "notAFunction"
foo()

Syntax Error on good code

The gross majority of the time a SyntaxError which points to an uninteresting line means there is an issue on the line before it (in this example, it’s a missing parenthesis):

def my_print():
x = (1 + 1
print(x)

Returns

File "", line 3
print(x)

^

SyntaxError: invalid syntax

The most common reason for this issue is mismatched parentheses/brackets, as the example shows.

There is one major caveat for print statements in Python 3:

Python 3.x Version ≥ 3.0

print "hello world" File "", line 1 print "hello world"

^

SyntaxError: invalid syntax

Because the print statement was replaced with the print() function, so you want:

print("hello world") # Note this is valid for both Py2 & Py3

IndentationErrors (or indentation SyntaxErrors)

In most other languages indentation is not compulsory, but in Python (and other languages: early versions of FORTRAN, Makefiles, Whitespace (esoteric language), etc.) that is not the case, what can be confusing if you come from another language, if you were copying code from an example to your own, or simply if you are new.

IndentationError/SyntaxError: unexpected indent

This exception is raised when the indentation level increases with no reason.

Example

There is no reason to increase the level here:

Python 2.x Version ≥ 2.0 Version ≤ 2.7

print "This line is ok"
print "This line isn't ok"

Python 3.x Version ≥ 3.0

print("This line is ok")
print("This line isn't ok")

Here there are two errors: the last one and that the indentation does not match any indentation level. However just one is shown:

Python 2.x Version ≥ 2.0 Version ≤ 2.7

print "This line is ok"
print "This line isn't ok"

Python 3.x Version ≥ 3.0

print("This line is ok")
print("This line isn't ok")

IndentationError/SyntaxError: unindent does not match any outer indentation level

Appears you didn’t unindent completely.

Example

Python 2.x Version ≥ 2.0 Version ≤ 2.7

def foo():
print "This should be part of foo()"
print "ERROR!"
print "This is not a part of foo()"

Python 3.x Version ≥ 3.0

print("This line is ok")
print("This line isn't ok")

IndentationError: expected an indented block

After a colon (and then a new line) the indentation level has to increase. This error is raised when that didn’t happen.

Example

if ok:
doStuff()

Note: Use the keyword pass (that makes absolutely nothing) to just put an if, else, except, class, method or

definition but not say what will happen if called/condition is true (but do it later, or in the case of except: just do nothing):

def foo():
pass

IndentationError: inconsistent use of tabs and spaces in indentation Example

def foo():
if ok:
return "Two != Four != Tab"
return "i don't care i do whatever i want"

How to avoid this error

Don’t use tabs. It is discouraged by PEP8, the style guide for Python.

Set your editor to use 4 spaces for indentation.

Make a search and replace to replace all tabs with 4 spaces.

Make sure your editor is set to display tabs as 8 spaces, so that you can realize easily that error and fix it.

See this question if you want to learn more.

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment