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:

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:

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:

Best practices include:

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:

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:

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: