You execute your Python program and you see an error, “NameError: name … is not defined”. What does it mean?
In this article I will explain you what this error is and how you can quickly fix it.
What causes a Python NameError?
The Python NameError occurs when Python cannot recognise a name in your program. A name can be either related to a built-in function or to something you define in your program (e.g. a variable or a function).
Let’s have a look at some examples of this error, to do that I will create a simple program and I will show you common ways in which this error occurs during the development of a Python program.
A Simple Program to Print the Fibonacci Sequence
We will go through the creation of a program that prints the Fibonacci sequence and while doing that we will see 4 different ways in which the Python NameError can appear.
First of all, to understand the program we are creating let’s quickly introduce the Fibonacci sequence.
In the Fibonacci sequence every number is the sum of the two preceding numbers in the sequence. The sequence starts with 0 and 1.
Below you can see the first 10 numbers in the sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
That’s pretty much everything we need to know to create a Python program that generates this sequence.
Let’s get started!
To simplify things our Python program will print the sequence starting from the number 1.
Here is the meaning of the variables n1, n2 and n:
VariableMeaningnnth term of the sequencen1(n-1)th term of the sequencen2(n-2)th term of the sequence
And here is our program.
At each iteration of the while loop we:
- Calculate the nth term as the sum of the (n-2)th and (n-1)th terms.
- Assign the value of the (n-1)th terms to the (n-2)th terms.
- Assign the value of the nth terms to the (n-1)th terms.