Name is not defined python что делать
Перейти к содержимому

Name is not defined python что делать

  • автор:

Name is not defined python что делать

This issue happens when you try to invoke a class within a module without specifying the module.

Initial Steps Overview

Detailed Steps

1) Change the call to reference the module

Above we see that Foo.bar() doesn’t work, which is because we only have access to the module foo and not the class within it. To access this class we could instead do foo.Foo.bar() . In this case, foo is the module name and Foo is the class name.

You would have a similar problem if the casing of the class was the same as the module you would just receive a different error.

2) Change the import to load the class directly

Given the example shown in step #1, the import within main can be changed to make the call work. We simply need to use the following format from <modulename> import <classname> . So in our example, this would be:

Python NameError: name is not defined

I have a python script and I am receiving the following error:

Here is the code that causes the problem:

This is being run with Python 3.3.0 under Windows 7 x86-64.

Why can’t the Something class be found?

wjandrea's user avatar

4 Answers 4

Define the class before you use it:

You need to pass self as the first argument to all instance methods.

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

This will also result in

That’s because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

Tomasz Bartkowiak's user avatar

You must define the class before creating an instance of the class. Move the invocation of Something to the end of the script.

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

I got the same error below:

NameError: name ‘name’ is not defined

When I don’t define the getter method with @property while the setter and deleter are defined as shown below:

Python Error: Name Is Not Defined. Let’s Fix It

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:

Variable Meaning
n nth term of the sequence
n1 (n-1)th term of the sequence
n2 (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.

We assign the values to the (n-2)th and (n-1)th terms so we can use them in the next iteration of the while loop to calculate the value of the nth term.

I run the program, and….

This syntax error is telling us that the name count is not defined.

It basically means that the count variable is not defined.

So in this specific case we are using the variable count in the condition of the while loop without declaring it before. And because of that Python generates this error.

Let’s define count at the beginning of our program and try again.

And if we run the program, we get…

Lesson 1: The Python NameError happens if you use a variable without declaring it.

Order Really Counts in a Python Program

Now I want to create a separate function that calculates the value of the nth term of the sequence.

In this way we can simply call that function inside the while loop.

In this case our function is very simple, but this is just an example to show you how we can extract part of our code into a function.

This makes our code easier to read (imagine if the calculate_nth_term function was 50 lines long):

And here is the output of the program…

Wait…a NameError again.

We have defined the function we are calling so why the error?

Because we are calling the function calculate_nth_term before defining that same function.

We need to make sure the function is defined before being used.

So, let’s move the function before the line in which we call it and see what happens:

Our program works well this time!

Lesson 2: Make sure a variable or function is declared before being used in your code (and not after).

Name Error With Built-in Functions

I want to improve our program and stop its execution if the user provides an input that is not a number.

With the current version of the program this is what happens if something that is not a number is passed as input:

That’s not a great way to handle errors.

A user of our program wouldn’t know what to do with this error…

We want to exit the program with a clear message for our user if something different that a number is passed as input to the program.

To stop the execution of our program we can use the exit() function that belongs to the Python sys module.

The exit function takes an optional argument, an integer that represents the exit status status of the program (the default is zero).

Let’s handle the exception thrown when we don’t pass a number to our program. We will do it with the try except statement

Bad news, at the end you can see another NameError…it says that sys is not defined.

That’s because I have used the exit() function of the sys module without importing the sys module at the beginning of my program. Let’s do that.

Here is the final program:

And when I run it I can see that the exception is handled correctly:

Lesson 3: Remember to import any modules that you use in your Python program.

Catch Any Misspellings

The NameError can also happen if you misspell something in your program.

For instance, let’s say when I call the function to calculate the nth term of the Fibonacci sequence I write the following:

As you can see, I missed the ‘h’ in ‘nth’:

Python cannot find the name “calculate_nt_term” in the program because of the misspelling.

This can be harder to find if you have written a very long program.

Lesson 4: Verify that there are no misspellings in your program when you define or use a variable or a function. This also applies to Python built-in functions.

Conclusion

You now have a guide to understand why the error “NameError: name … is not defined” is raised by Python during the execution of your programs.

Let’s recap the scenarios I have explained:

  • The Python NameError happens if you use a variable without declaring it.
  • Make sure a variable or function is declared before being used in your code (and not after).
  • Remember to import any modules that you use in your Python program.
  • Verify that there are no misspellings in your program when you define or use a variable or a function. This also applies to Python built-in functions.

Does it make sense?

If you have any questions feel free to post them in the comments below ��

I have put together for you the code we have created in this tutorial, you can get it here.

And if you are just getting started with Python have a look at this free checklist I created to build your Python knowledge.

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

How to Solve an Undefined Variable NameError in Python

How to Solve an Undefined Variable NameError in Python

In Python, a NameError: name ‘x’ is not defined error is raised when the program attempts to access or use a variable that has not been defined or assigned a value. This can happen if the variable is spelled incorrectly, or if it is accessed before it has been defined.

What Causes Undefined Variable

In Python, a variable is not created until a value is assigned to it. If an attempt is made to use a variable before it is defined, a NameError: name ‘x’ is not defined error is thrown.

The error message typically includes the name of the variable that is causing the problem and the line of code where the error occurred.

Python Undefined Variable Example

Here’s an example of a Python NameError: name ‘x’ is not defined thrown when using an undefined variable:

In this example, an undefined variable x is used in the range() function, throwing the NameError: name ‘x’ is not defined error:

How to Solve Undefined Variable in Python

To solve the NameError: name ‘x’ is not defined error in Python, you need to make sure that the variable is properly defined and assigned a value before it is used. The variable should also be referenced correctly, with the correct case and spelling.

The earlier example can be updated to define the variable before it is used:

Here, x is defined by being assigned a value before it is used in the range() function. The above code executes successfully, producing the correct output as expected:

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *