Reputation: 977
I have conditions and need to define var in them and use that out of this conditions. This is my codes:
if 1 < (process_time % 60):
final_process_time = 'process time is: ' + str(process_time) + ' sec!'
elif 1 <= (process_time % 60) < 60:
process_time = process_time / 60
final_process_time = 'process time is: ' + str(process_time) + ' min!'
elif 60 <= (process_time % 60):
process_time = process_time / 3600
final_process_time = 'process time is: ' + str(process_time) + ' hour(s)!'
print(final_process_time)
I got this error:
local variable 'final_process_time' referenced before assignment
Hints: I tested these solutions, but none of them responded:
set final_process_time to `global` # Error: name 'final_process_time' is not defined
Define final_process_time ='' Before conditions # Result: nothing set to this var
Attached : Some of you suggested that I put more of my code to fix the bug in this section. My entire codes:(of course, some absolutely unrelated items have not been added)
def excel_report(request):
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
....
TITLES_LIST = [
['user', 'title', 'explains', 'organization', 'post', 'time_start', 'time_end'],
....
]
FILE_NAME = 'report-' + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M") + '.xlsx'
# writer = pd.ExcelWriter(FILE_NAME, engine='xlswriter')
if request.method == 'POST':
if 'job_record' in request.POST:
time_start_process = time.time()
resumes = JobRecord.objects.all().values(*(TITLES_LIST[0][0]))
titles_list = TITLES_LIST[0][0]
worksheet = workbook.add_worksheet('Job Resume')
worksheet.write_row('A1', titles_list, title_styles)
for i in range(1, len(resumes) + 1):
k = i - 1
for j in range(len(titles_list) - 2):
worksheet.write(i, j, resumes[k][titles_list[j]], body_styles)
worksheet.write(i, 5, resumes[k]['time_start'], time_style)
worksheet.write(i, 6, resumes[k]['time_end'], time_style)
process_time = time.time() - time_start_process
if 1 < (process_time % 60):
final_process_time = 'process time is: ' + str(process_time) + ' sec!'
elif 1 <= (process_time % 60) < 60:
process_time = process_time / 60
final_process_time = 'process time is: ' + str(process_time) + ' min!'
elif 60 <= (process_time % 60):
process_time = process_time / 3600
final_process_time = 'process time is: ' + str(process_time) + ' hour(s)!'
worksheet = workbook.add_worksheet('process sheet')
worksheet.write('A1', 'Process Time', title_styles)
worksheet.write('A2', final_process_time, title_styles)
workbook.close()
output.seek(0)
response = HttpResponse(output,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % FILE_NAME
return response
Upvotes: 0
Views: 71
Reputation: 236034
Either set final_process_time
to a meaningful value before the conditions, or add an else
clause where you, again, set it to a meaningful value. Don't make it global
, that has nothing to do with the problem.
Upvotes: 4