• Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Python program to find power of a number
  • Python program to calculate gross pay
  • Python - Ways to print longest consecutive list without considering duplicates element
  • Python - Golomb Encoding for b=2n and b!=2n
  • SpongeBob Mocking Text Generator - Python
  • Python - Frequency of x follow y in Number
  • Spelling checker in Python
  • Python | Visualizing O(n) using Python
  • Operations on Python Counter
  • Python | Convert list of strings to space separated string
  • Python | Ways to convert hex into binary
  • Smart calculator in Python
  • Python | Check possible bijection between sequence of characters and digits
  • Python | Check if string is a valid identifier
  • Download Anything to Google Drive using Google colab
  • Python program to convert POS to SOP
  • Python code to convert SOP to POS
  • Python | Calculate geographic coordinates of places using google geocoding API
  • Python implementation of automatic Tic Tac Toe game using random number

How to Fix – UnboundLocalError: Local variable Referenced Before Assignment in Python

Developers often encounter the  UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches.

What is UnboundLocalError: Local variable Referenced Before Assignment?

This error occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Below, are the reasons by which UnboundLocalError: Local variable Referenced Before Assignment error occurs in  Python :

Nested Function Variable Access

Global variable modification.

In this code, the outer_function defines a variable ‘x’ and a nested inner_function attempts to access it, but encounters an UnboundLocalError due to a local ‘x’ being defined later in the inner_function.

In this code, the function example_function tries to increment the global variable ‘x’, but encounters an UnboundLocalError since it’s treated as a local variable due to the assignment operation within the function.

Solution for Local variable Referenced Before Assignment in Python

Below, are the approaches to solve “Local variable Referenced Before Assignment”.

In this code, example_function successfully modifies the global variable ‘x’ by declaring it as global within the function, incrementing its value by 1, and then printing the updated value.

In this code, the outer_function defines a local variable ‘x’, and the inner_function accesses and modifies it as a nonlocal variable, allowing changes to the outer function’s scope from within the inner function.

Please Login to comment...

  • Python Errors
  • Python How-to-fix
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Fixing Python UnboundLocalError: Local Variable ‘x’ Accessed Before Assignment

Understanding unboundlocalerror.

The UnboundLocalError in Python occurs when a function tries to access a local variable before it has been assigned a value. Variables in Python have scope that defines their level of visibility throughout the code: global scope, local scope, and nonlocal (in nested functions) scope. This error typically surfaces when using a variable that has not been initialized in the current function’s scope or when an attempt is made to modify a global variable without proper declaration.

Solutions for the Problem

To fix an UnboundLocalError, you need to identify the scope of the problematic variable and ensure it is correctly used within that scope.

Method 1: Initializing the Variable

Make sure to initialize the variable within the function before using it. This is often the simplest fix.

Method 2: Using Global Variables

If you intend to use a global variable and modify its value within a function, you must declare it as global before you use it.

Method 3: Using Nonlocal Variables

If the variable is defined in an outer function and you want to modify it within a nested function, use the nonlocal keyword.

That’s it. Happy coding!

Next Article: Fixing Python TypeError: Descriptor 'lower' for 'str' Objects Doesn't Apply to 'dict' Object

Previous Article: Python TypeError: write() argument must be str, not bytes

Series: Common Errors in Python and How to Fix Them

Related Articles

  • Python Warning: Secure coding is not enabled for restorable state
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js

IMAGES

  1. UnboundLocalError: Local Variable Referenced Before Assignment

    unboundlocalerror local variable 'print' referenced before assignment

  2. "Fixing UnboundLocalError: Local Variable Referenced Before Assignment

    unboundlocalerror local variable 'print' referenced before assignment

  3. UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'print' referenced before assignment

  4. Unboundlocalerror local variable error referenced before assignment

    unboundlocalerror local variable 'print' referenced before assignment

  5. Python :Python 3: UnboundLocalError: local variable referenced before

    unboundlocalerror local variable 'print' referenced before assignment

  6. PYTHON : Python scope: "UnboundLocalError: local variable 'c

    unboundlocalerror local variable 'print' referenced before assignment

VIDEO

  1. Java Programming # 44

  2. Rapture Before Assignment Completion?

  3. local variable referenced before assignment error in python in hindi

  4. Prophetic Word

  5. Alignment before assignment! You need to get your alignment right before getting your assignment

  6. Local and Global Variables in Python (Python Tutorial

COMMENTS

  1. How to Fix

    Output. Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment

  2. UnboundLocalError: local variable ... referenced before

    There isn't a standard way to handle this situation. Common approaches are: 1. make sure that the variable is initialized in every code path (in your case: including the else case) 2. initialize the variable to some reasonable default value at the beginning. 3. return from the function in the code paths which cannot provide a value for the ...

  3. Fixing Python UnboundLocalError: Local Variable 'x' Accessed

    2 Solutions for the Problem. 2.1 Method 1: Initializing the Variable. 2.2 Method 2: Using Global Variables. 2.3 Method 3: Using Nonlocal Variables.