Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug?

#1
Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug?

The Python interpreter throws the NameError exception if it encounters an undefined variable or function name. To fix it, you must figure out why the variable is not defined—the most frequent bugs are (1) to use the variable of function name in the code before it was defined, or (2) to misspell the name in either the definition or the usage.

Have a look at the minimal example in our interactive code shell:

Exercise: Define variable some_variable before you use it and fix the bug!

Note: All the explanations and solutions provided below have been verified using Python 3.8.5.

Problem


When one is beginning to write Python code, they will come across the NameError exception. The Python Interpreter throws this exception to state an error.  Experienced Python coders, even Python legends like Guido (I suppose), run into these errors, every now and then. In its simplest form, the error looks like something similar to the following:

>>> print(some_variable)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'some_variable' is not defined
>>>

Desired Output


This article aims to help the reader understand some of the most common reasons for this error.

>>> print(some_variable)
hello world
>>>

The desired output, assumes the variable some_variable, points to the string "hello world".  In other words, the desired output would be an error free run of the reader’s Python code.

Background


Python is an interpreted language. This means, it interprets any Python code, line by line, from the beginning of the code to the end. The execution usually stops at the first error which the Python Interpreter encounters.  The error message usually prints out helpful information about the problem.  In most cases, the reader can debug, deduce and locate the erroneous syntax and fix it.  This blog will attempt to describe one such common problem called the NameError.

Missing Variable Definition


One common cause of the NameError exception is a missing variable definition. As mentioned before, Python is an interpreted language. This means that the reader should define the variables before using them. Consider the following code. The reader is eager to try out some basic Python code real quick.  So they fire up the Python interpreter to try out their fresh Python skills.

>>> print(some_variable)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'some_variable' is not defined
>>>

Oops!!! The reader finds out they have not defined some_variable, before they used it! Fix this problem as shown below. Define some_variable before using it!

>>> some_variable = ‘Hello World’
>>> print(some_variable)
Hello World
>>>

Misspelled Variable Name


Misspelled variable names can be erroneous in a similar way. Consider the following example code.

>>> som_variable = ‘Hello World’
>>> print(some_variable)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'some_variable' is not defined
>>>

Note: som_variable is not the same as some_variable (i.e. missing 'e')

Missing Function Definitions


Another common cause of the NameError exception is a missing function definition. Like variable definitions, the reader should define any function, before using it. Consider the following code.

>>> some_other_string = ‘Hello World’
>>> some_function(some_other_string)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'some_function' is not defined
>>>

Again, the function 'some_function' is not defined before its use.
Fix this problem as shown below. Define 'some_function' before using it.

>>> def some_function(some_string):
... print(some_string)
... >>> some_other_string = ‘Hello World’
>>> some_function(some_other_string)
Hello World
>>>

Misspelled Function Name


Misspelled function names can be erroneous in a similar way. Consider the following example code.

>>> def som_function(some_string):
... print(some_string)
... >>> some_other_string = ‘Hello World’
>>> some_function(some_other_string)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'some_function' is not defined
>>>

Note: 'som_function' is not the same as 'some_function' (i.e. missing 'e')

Wrong Scope


Yet another common cause of the NameError exception is the use of the variable in the wrong scope. Consider the following example.

>>> ## Define the function some_function()
>>> def some_function():
... a_local_variable = ‘I am Local…’
... print("Printing a Local variable from within a function definition: " + a_local_variable)
... >>> ## Call some_function()
>>> some_function()
Printing a Local variable from within a function definition: I am Local...
>>> >>> ## Try to print "a_local_variable" from outside the function definition
>>> print("Attempting to print the variable from outside some_function(): " + a_local_variable)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'a_local_variable' is not defined
>>>

The NameError exception occurred because a_local_variable got called from outside its function scope. 
One way to fix this is by defining a_local_variable as a global variable instead. Consider the following example.

>>> ## Define a Global Variable
>>> a_global_variable = ‘I am global…’
>>> >>> ## Define the function some_function()
>>> def some_function():
... print("Printing the Global variable from within a function definition: " + a_global_variable)
... >>> ## Call some_function()
>>> some_function()
Printing the Global variable from within a function definition: I am global...
>>> >>> ## Try to print "a_global_variable" from outside the function definition
>>> print("Attempting to print the Global variable from outside some_function(): " + a_global_variable)
Attempting to print the Global variable from outside some_function(): I am global…
>>>

Unquoted String In print() Statement


Forgetting to quote strings in the print() statement can cause the NameError exception. This does not happen often, but it is good to know that it can happen. The reader is more likely to see a SyntaxError rather than a NameError. Consider the following examples…

>>> print(Hello)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'Hello' is not defined >>> print(Hello World) File "<stdin>", line 1 print(Hello World) ^
SyntaxError: invalid syntax
>>>

In both the examples above, unquoted strings cause errors. NameError in one case and SyntaxError in another.

In this case, the fix is simple. Enclose the strings in quotes.

>>> print(‘Hello’)
Hello >>> print(‘Hello World’)
Hello World

Conclusion


Such errors will happen in the reader’s coding life. The important thing is to learn from it and move on.  Over time the reader will get better at coding, as they incorporate good coding habits. Such errors happen lesser and lesser as the reader gets more experienced.

Finxter Academy


This blog was brought to you by Girish, a student of Finxter Academy. You can find his Upwork profile here.

References


All research for this blog article was done using Python Documents, the Google Search Engine and the shared knowledge-base of the Finxter Academy and the Stack Overflow Communities. Concepts and ideas were also researched from the Boston University and Career Karma communities.

The post Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? first appeared on Finxter.



https://www.sickgaming.net/blog/2020/10/...tupid-bug/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 18 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 18 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 29 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 31 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 32 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 34 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 31 09-25-2020, 07:51 PM
Last Post: xSicKxBot
  [Tut] Python One Line Dictionary xSicKxBot 0 40 09-21-2020, 05:58 PM
Last Post: xSicKxBot
  [Tut] Python Import Error (ModuleNotFoundError) xSicKxBot 0 33 09-20-2020, 04:15 PM
Last Post: xSicKxBot
  [Tut] Python Unicode Encode Error xSicKxBot 0 34 09-19-2020, 03:25 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
Xbox one SDK Leaked: homebrew coming soo...
Last Post: DanielChapell
Today 05:51 PM
» Replies: 1
» Views: 1762
News - Here's How The Walking Dead Is Fi...
Last Post: xSicKxBot
Today 05:50 PM
» Replies: 0
» Views: 1
(Indie Deal) PlugInDigital & Kalypso Str...
Last Post: xSicKxBot
Today 05:06 PM
» Replies: 0
» Views: 2
(Free Game Key) Costume Quest 2 & Layers...
Last Post: xSicKxBot
Today 05:05 PM
» Replies: 0
» Views: 2
News - Destiny 2 Hotfix 2.9.2.2
Last Post: xSicKxBot
Today 01:53 PM
» Replies: 0
» Views: 2
News - The Video Game History Foundation...
Last Post: xSicKxBot
Today 01:52 PM
» Replies: 0
» Views: 3
News - French charity steam Z Event rais...
Last Post: xSicKxBot
Today 01:52 PM
» Replies: 0
» Views: 3
News - Borat 2 Review Roundup: Very Nice...
Last Post: xSicKxBot
Today 11:18 AM
» Replies: 0
» Views: 4
Mobile - Win yourself a free copy of sha...
Last Post: xSicKxBot
Today 09:07 AM
» Replies: 0
» Views: 3
[Tut] Top 3 Freelance Developer Contract...
Last Post: xSicKxBot
Today 04:49 AM
» Replies: 0
» Views: 3

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020