Unboundlocalerror local variable referenced before assignment

Есть кусок кода:

Я понял, что при сравнении не видит переменную, но как я только не пытался ее объявить, все равно точно такую же ошибку выдает.

  • Вопрос задан более года назад
  • 722 просмотра

Вот он — результат бессистемного обучения! Никто не читает учебников.

Истина в простоте! Как я мог забыть про это.

The following code gives the error UnboundLocalError: local variable ‘Var1’ referenced before assignment :

How can I fix this? Thanks for any help!

5 Answers 5

You can fix this by passing parameters rather than relying on Globals

This is because, even though Var1 exists, you’re also using an assignment statement on the name Var1 inside of the function ( Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function’s scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope’s Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you’d like to use them to accomplish what your code is implying, you can simply add:

inside the top of your function. This will tell Python that you don’t intend to define a Var1 or Var2 variable inside the function’s local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Читайте также:  Windows server 2008 standard key

Ошибка:

UnboundLocalError: local variable ‘row’ referenced before assignment

2 ответа 2

Ошибка говорит о том, что на момент проверки переменная row у вас еще не инициализирована. Она у вас инициализируется в другой ветке if выше. Я предполагаю, что нужно вынести часть кода из первой ветки if до самого if , будет что-то вроде этого:

Хотя, могу ошибаться, т.к. не знаю логики работы вашей программы.

У вас в сообщении об ошибке написано, что переменная var еще не назначена, т.е. ей нужно присвоить какое-либо значение, например row=’spam’ , перед условным выражение if

Всё ещё ищете ответ? Посмотрите другие вопросы с метками python sqlite или задайте свой вопрос.

Похожие

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

дизайн сайта / логотип © 2020 Stack Exchange Inc; пользовательское содержимое попадает под действие лицензии cc by-sa 4.0 с указанием ссылки на источник. rev 2020.1.17.35809

Rate this post

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *