NameError: function is not defined

Loading

The error message:

NameError: name 'function_name' is not defined

occurs when Python cannot recognize a function because it has not been defined or is used incorrectly.


1. Causes and Solutions

Cause 1: Calling a Function Before Defining It

Python reads the script from top to bottom. If you try to use a function before defining it, you’ll get a NameError.

Incorrect Code:

greet()  # Function is called before it's defined

def greet():
print("Hello!")

Error Output:

NameError: name 'greet' is not defined

Solution: Define the Function Before Calling It

def greet():  # Define function first
print("Hello!")

greet() # Then call it

Cause 2: Function Name is Misspelled

Python is case-sensitive, so even a small typo will cause this error.

Incorrect Code:

def greet():
print("Hello!")

greett() # Typo in function name

Error Output:

NameError: name 'greett' is not defined

Solution: Correct the Function Name

def greet():
print("Hello!")

greet() # Correct name

Cause 3: Function is Defined Inside a Scope but Called Outside

If a function is defined inside another function, it cannot be accessed globally.

Incorrect Code:

def outer():
def inner():
print("Inside inner function")

inner() # Error: 'inner' is not defined globally

Error Output:

NameError: name 'inner' is not defined

Solution: Call the Function Inside Its Scope

def outer():
def inner():
print("Inside inner function")

inner() # Call it inside

outer()

Cause 4: Importing a Function Incorrectly

If a function is inside another module but is not properly imported, Python will not recognize it.

Incorrect Code:

import math
math.squareroot(16) # 'squareroot' is incorrect

Error Output:

AttributeError: module 'math' has no attribute 'squareroot'

Solution: Use the Correct Function Name

import math
print(math.sqrt(16)) # Use 'sqrt' instead of 'squareroot'

2. Best Practices to Avoid the Error

  • Always define functions before calling them.
  • Check for spelling errors.
  • Be careful with scopes.
  • Import functions correctly if using external modules.

Leave a Reply

Your email address will not be published. Required fields are marked *