UnboundLocalError: local variable 'data' referenced before assignment

Open
#1,131 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
20/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
pandas, python
Domain
tooling

Research direction

Start with the code in the issue, especially outer_function and the loop that reads Sheet1. Run the example to reproduce the UnboundLocalError, then trace the paths where data is assigned and consumed; done means the example handles the relevant worksheet contents without referencing an unset local variable.

Written by the indexing model from the issue text.

Description

import xlsxwriter
import pandas as pd
import openpyxl
import pandas as pd

current=1
i = 0
counter=0

Create some Pandas dataframes from some data.

df1 = pd.DataFrame({'Data1': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data2': [21, 22, 23, 24,25]})
df3 = pd.DataFrame({'Data3': [31, 32, 33, 34,35,36]})
df4 = pd.DataFrame({'Data4': [41, 42, 43, 44,45,46,47]})
df5 = pd.DataFrame({'Data5': [51, 52, 53, 54,55,56,57,58]})

Create a Pandas Excel writer using XlsxWriter as the engine.

writer = pd.ExcelWriter('pandas_positioning.xlsx', engine='xlsxwriter')

Position the dataframes in the worksheet.

df1.to_excel(writer, sheet_name='Sheet1',startrow=0) # Default position, cell A1.
df2.to_excel(writer, sheet_name='Sheet1', startcol=0,startrow=5)
df3.to_excel(writer, sheet_name='Sheet1', startrow=0,startcol=11)
df3.to_excel(writer, sheet_name='Sheet1', startrow=0,startcol=18)
df3.to_excel(writer, sheet_name='Sheet1', startrow=0,startcol=26)

It is also possible to write the dataframe without the header and index.

#df4.to_excel(writer, sheet_name='Sheet1', startrow=7, startcol=4, header=False, index=False)

Close the Pandas Excel writer and output the Excel file.

writer.save()

def outer_function():
import xlrd
wb=xlrd.open_workbook('C:/Users/bened/pandas_positioning.xlsx')
sheet=wb.sheet_by_name('Sheet1')

for i in range(sheet.nrows):
    if(sheet.cell_value(i,0)=='Data3'):
            data=i
    d=0
    while(d<data):
        print('hi')
        break

outer_function()

how do i solve UnboundLocalError: local variable 'data' referenced before assignment
Dominant language
Python
Stars
35.4k
Forks
12.9k
Avg merge
2h 37m
Merged PRs (30d)
1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from geekcomputers/Python

All issues in geekcomputers/Python

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.