Name Errors in Python


TL ; DR:

  • A NameError occurs when Python sees a word it does not recognize. Some examples:

  • Misspelling a function name:

    prnt("Heyooo!") # NameError: name 'prnt' is not defined
    

  • Misspelling a variable name:

    animal = "parrot"
    print(anmal) # NameError: name 'anmal' is not defined
    

  • When Python encounters a name error, it immediately stops executing your code and throws a NameError instead.




Full lesson:

Humans are prone to making mistakes. Humans are also typically in charge of creating computer programs. To compensate, programming languages attempt to understand and explain mistakes made in their programs.

Here are two common errors that we encounter while writing Python code:


The NameError:

A NameError occurs when the Python interpreter sees a word it does not recognize. Some examples:

1. Misspelling a function's name:

prnt("My name is Andy")

2. Using a non-existent variable / Misspelling a variable's name:

animal = "parrot"
print(aniimal)

When we run this code we'll get a NameError: name 'aniimal' is not defined.


Assignment
Follow the Coding Tutorial and let's practice with errors!


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore NameError in Python, a common error that occurs when the interpreter encounters an unrecognized identifier. Understanding and resolving NameError is crucial for debugging and writing error-free code. This error often arises from simple mistakes such as typos in function or variable names.

Understanding the Basics

A NameError is raised when Python cannot find a local or global name. This typically happens due to:

  • Misspelling a function or variable name.
  • Using a variable before it is defined.
  • Referencing a variable that is out of scope.

Let's look at a simple example:

prnt("Hello, World!")  # NameError: name 'prnt' is not defined

In this example, the function print is misspelled as prnt, leading to a NameError.

Main Concepts

To avoid NameError, ensure that:

  • All variable and function names are spelled correctly.
  • Variables are defined before they are used.
  • Variables are within the correct scope.

Consider the following example:

animal = "parrot"
print(animal)  # Correct usage
print(anml)    # NameError: name 'anml' is not defined

Here, anml is a typo, causing a NameError.

Examples and Use Cases

Let's explore more examples to understand how NameError can occur in different contexts:

# Example 1: Misspelled function name
def greet():
    print("Hello!")

gret()  # NameError: name 'gret' is not defined

# Example 2: Variable used before definition
print(name)  # NameError: name 'name' is not defined
name = "Alice"

# Example 3: Variable out of scope
def outer_function():
    inner_variable = 10

print(inner_variable)  # NameError: name 'inner_variable' is not defined

Common Pitfalls and Best Practices

To avoid common pitfalls related to NameError:

  • Double-check the spelling of all identifiers.
  • Initialize variables before using them.
  • Be mindful of variable scope, especially in nested functions or loops.

Best practices include:

  • Using meaningful and consistent naming conventions.
  • Keeping functions and variable definitions close to their usage.
  • Regularly testing and debugging code to catch errors early.

Advanced Techniques

For advanced error handling, consider using try-except blocks to catch and handle NameError:

try:
    print(undeclared_variable)
except NameError as e:
    print(f"Error: {e}")

This approach allows your program to continue running even if a NameError occurs.

Code Implementation

Here is a comprehensive example demonstrating correct usage and handling of NameError:

# Correct usage of variables and functions
def display_message():
    print("Welcome to the Python tutorial!")

message = "Hello, Python!"
display_message()
print(message)

# Handling NameError using try-except
try:
    print(undefined_variable)
except NameError as e:
    print(f"Caught an error: {e}")

Debugging and Testing

To debug and test code for NameError:

  • Use print statements to check variable values and function calls.
  • Employ debugging tools like pdb to step through code.
  • Write unit tests to ensure functions and variables are correctly defined and used.

Example of a simple test case:

import unittest

class TestNameError(unittest.TestCase):
    def test_variable(self):
        animal = "parrot"
        self.assertEqual(animal, "parrot")

    def test_function(self):
        def greet():
            return "Hello!"
        self.assertEqual(greet(), "Hello!")

if __name__ == "__main__":
    unittest.main()

Thinking and Problem-Solving Tips

When encountering a NameError:

  • Carefully read the error message to identify the unrecognized name.
  • Check the spelling and definition of the name in your code.
  • Ensure the name is within the correct scope.

Practice by writing small programs and intentionally introducing errors to understand how they occur and how to fix them.

Conclusion

Mastering the resolution of NameError is essential for efficient debugging and coding in Python. By understanding the common causes and implementing best practices, you can write more reliable and error-free code. Keep practicing and exploring further to enhance your programming skills.

Additional Resources

For further reading and practice: