I am pretty new to programming and I have made an app which works fine but I get warnings saying «Name «X» can be undefined». What does this mean and how could I get rid of the warning? I am using Python 3.8 with Intelij IDE 2020.1.
Here is a screenshot of my issue:
Here is a minimum repo of my code:
print("1. school a n2. school b")
while True:
try:
school_number = int(input("nEnter the number of what school you are at: "))
break
except ValueError:
print("That was an invalid number. Please try again...n")
current_day = input("Please enter what day it is (mon/tue etc): ".lower())
if school_number == 1:
school_name = "school A"
cost = (7.50 * 2)
leave_time_multiplier = 1.15
if current_day == "mon":
start_time = 09.30
finish_time = 14.30
else:
pass
if school_number == 2:
school_name = "school B"
cost = (9.50 * 2)
leave_time_multiplier = 1.25
if current_day == "mon":
start_time = 17.00
finish_time = 20.30
else:
pass
# renames the days
if current_day == "mon":
day = "Monday"
else:
day = "Other"
leave_time = start_time - leave_time_multiplier - 1
print("nOn {} at {}: It will cost {:.2f} return. You start at {:.2f} and finish at {:.2f} You should leave at"
"{:.2f}".format(day, school_name, cost, start_time, finish_time, leave_time))
Автор оригинала: Girish Rao.
Переводчик Python бросает NameError
Исключение, если он встречает неопределенную переменную или имя функции. Чтобы исправить это, вы должны выяснить, почему переменная не определена – самые частые ошибки (1) для использования переменной или имени функции в коде до Это было определено или (2), чтобы пропустить имя в определении или использовании.
Посмотрите на минимальный пример в нашем интерактивном коде Shell:
Упражнение : Определите переменную quote_variable. Прежде чем использовать его и исправить ошибку!
Примечание : Все объяснения и решения, приведенные ниже, были проверены с использованием Python 3.8.5.
Проблема
Когда человек начинает писать код Python, они столкнутся с NameError исключение. Переводчик Python бросает это исключение для состояния ошибки. Опытные кодеры Python, даже Легенды Python, как Guido (Я полагаю), вдаю в эти ошибки, время от времени. В его простейшей форме ошибка выглядит как что-то похожее на следующее:
>>> print(some_variable) Traceback (most recent call last): File "", line 1, in NameError: name 'some_variable' is not defined >>>
Желаемый вывод
Эта статья направлена на помощь читателю понять некоторые из наиболее распространенных причин этой ошибки.
>>> print(some_variable) hello world >>>
Желаемый выход, предполагает переменную quote_variable
, указывает на строку "
Здравствуйте, мир "
Отказ Другими словами, желаемый вывод будет бесплатным запуском кода Python Reader Python.
Фон
Python – это интерпретированный язык. Это означает, что он интерпретирует любой код Python, строка по линии, с начала кода до конца. Выполнение обычно останавливается при первой ошибке, который столкнулся с переводчиком Python. Сообщение об ошибке обычно печатает полезную информацию о проблеме. В большинстве случаев читатель может отладки, вывести и находить ошибочный синтаксис и исправить его. Этот блог попытается описать одну такую общую проблему, называемую NameError Отказ
Отсутствующее определение переменной
Одна общая причина NameError Исключение – это отсутствующее определение переменной. Как уже упоминалось ранее, Python является интерпретированным языком. Это означает, что читатель должен определять переменные перед использованием их. Рассмотрим следующий код. Читатель стремится попробовать какой-то основной код Python Real быстро. Таким образом, они уволяют переводчик Python, чтобы попробовать их свежие навыки Python.
>>> print(some_variable) Traceback (most recent call last): File "", line 1, in NameError: name 'some_variable' is not defined >>>
Ой !!! Читатель узнает, что они не определены quote_variable
, прежде чем они использовали это! Исправьте эту проблему, как показано ниже. Определить quote_variable
перед использованием этого!
>>> some_variable = 'Hello World' >>> print(some_variable) Hello World >>>
Имя переменной с ошибками
Имена переменной с ошибками ошибок могут быть ошибочными аналогичным образом. Рассмотрим следующий пример код.
>>> som_variable = 'Hello World' >>> print(some_variable) Traceback (most recent call last): File "", line 1, in NameError: name 'some_variable' is not defined >>>
Примечание : som_variable.
не то же самое, что quote_variable.
(то есть отсутствует 'E'
)
Отсутствующие функции определения
Еще одна общая причина NameError Исключение представляет собой недостающее определение функции. Как и переменные определения, читатель должен определить любую функцию, прежде чем использовать его. Рассмотрим следующий код.
>>> some_other_string = 'Hello World' >>> some_function(some_other_string) Traceback (most recent call last): File "", line 1, in NameError: name 'some_function' is not defined >>>
Опять же, функция «Некоторые_функция»
не определен до его использования. Исправьте эту проблему, как показано ниже. Определить «Некоторые_функция»
перед использованием этого.
>>> def some_function(some_string): ... print(some_string) ... >>> some_other_string = 'Hello World' >>> some_function(some_other_string) Hello World >>>
Название функции с ошибками
Имена функций с ошибками ошибок могут быть ошибочными похожими. Рассмотрим следующий пример код.
>>> def som_function(some_string): ... print(some_string) ... >>> some_other_string = 'Hello World' >>> some_function(some_other_string) Traceback (most recent call last): File "", line 1, in NameError: name 'some_function' is not defined >>>
Примечание : 'som_function'
не то же самое, что «Некоторые_функция»
(то есть отсутствует 'E'
)
Неправильный объем
Еще одна общая причина NameError Исключение – это использование переменной в неправильном объеме. Рассмотрим следующий пример.
>>> ## Define the function some_function() >>> def some_function(): ... a_local_variable = 'I am Local…' ... print("Printing a Local variable from within a function definition: " + a_local_variable) ... >>> ## Call some_function() >>> some_function() Printing a Local variable from within a function definition: I am Local... >>> >>> ## Try to print "a_local_variable" from outside the function definition >>> print("Attempting to print the variable from outside some_function(): " + a_local_variable) Traceback (most recent call last): File "", line 1, in NameError: name 'a_local_variable' is not defined >>>
NameError Исключение произошло потому, что a_local_variable
вызвано из-за внешнего объема функций. Один из способов исправить это, определяя a_local_variable
в качестве глобальной переменной вместо этого. Рассмотрим следующий пример.
>>> ## Define a Global Variable >>> a_global_variable = 'I am global…' >>> >>> ## Define the function some_function() >>> def some_function(): ... print("Printing the Global variable from within a function definition: " + a_global_variable) ... >>> ## Call some_function() >>> some_function() Printing the Global variable from within a function definition: I am global... >>> >>> ## Try to print "a_global_variable" from outside the function definition >>> print("Attempting to print the Global variable from outside some_function(): " + a_global_variable) Attempting to print the Global variable from outside some_function(): I am global… >>>
Unquoted String in Print ()
Забывая цитировать строки в Печать ()
Заявление может вызвать NameError исключение. Это не происходит часто, но хорошо знать, что это может произойти. Читатель, скорее всего, увидит SyntaxError а не NameError Отказ Рассмотрим следующие примеры …
>>> print(Hello) Traceback (most recent call last): File "", line 1, in NameError: name 'Hello' is not defined >>> print(Hello World) File "", line 1 print(Hello World) ^ SyntaxError: invalid syntax >>>
В приведенных выше примерах вышеупомянутые строки вызывают ошибки. NameError в одном случае и SyntaxError в другой.
В этом случае исправление просто. Приложите струны в цитатах.
>>> print('Hello') Hello >>> print('Hello World') Hello World
Заключение
Такие ошибки произойдут в кодировании читателя. Важно учиться у него и двигаться дальше. Со временем читатель станет лучше в кодировании, поскольку они включают хорошие привычки кодирования. Такие ошибки происходят меньше и меньше, поскольку читатель становится более опытным.
Финктерская академия
Этот блог был доставлен вам Girish , студент Финктерская академия . Вы можете найти его Профиль намного здесь Отказ
использованная литература
Все исследования для этой статьи в блоге было сделано с использованием Python Documents , Поисковая система Google и общая база знаний Финктерская академия и Переполнение стека Общины. Концепции и идеи были также исследованы из Бостонский университет и Карьера карма общины.
Оригинал: “https://blog.finxter.com/pythons-nameerror/”
-
2020-12-01, 11:06 AM (ISO 8601)
—
Top
—
End—
#1
Bugbear in the Playground
Name can be Undefined (python3)
I am fairly new at coding and am putting together a system where I can apply a bonus and a penalty to a dice roll the system is working, but PyCharm is giving me a warning that reads ‘Name ‘mod_bonus’ can be undefined’ and I cannot find information on what exactly this means and what to do about it.
I think the warning is referring to it detecting the possibility ‘mod_bonus’ may end up undefined, to judge by the wording, but I think the loop on it would prevent that?
The relevant section of code is the following:
Spoiler
Show
Code:
# Takes result of dice roll and then offers to apply a further modifier. while True: apply_mod = input("Apply Modifier? yes/no") if apply_mod == "yes": # finds bonus while True: try: mod_bonus = int(input("Input Bonus")) break except ValueError: continue # finds penalty while True: try: mod_penalty = int(input("Input Penalty")) except ValueError: continue # finds modifier and adds to prior roll final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier)) break elif apply_mod == "no": print("Random Selected Number is: " + str(dice)) break
-
2020-12-01, 11:26 AM (ISO 8601)
—
Top
—
End—
#2
Troll in the Playground
Re: Name can be Undefined (python3)
If I’m not mistaken, the error is caused by those ‘try’ blocks. i think they make it possible to arrive at the final_midifier calculation without defining mod_bonus, which cause the error.
I’m not at my computer though, so I can’t check this suspicion.
-
2020-12-01, 12:47 PM (ISO 8601)
—
Top
—
End—
#3
Titan in the Playground
Re: Name can be Undefined (python3)
I think DeTess is right. If the entry of mod_bonus fails, it will be undefined later on. You might be able to fix this by initializing the variable to 0. Probably should do the same for mod_penalty as well, just to be safe. Or set them to 0 as part of the failure exception?
Also, you should check your math or your input of of mod_penalty to see if the user enters a positive or negative number. I would expect to put in a negative number for a penalty, but then you’re subtracting it when you do the math part (a double negative). Easiest fix is to subtract the absolute value of mod_penalty using abs(mod_penalty).
EDIT: Alright, I’m not a Python expert. I noticed the extra while loops and you might be correct that the first try should repeat until it succeeds. In that case, I’m not sure how the variable could be undefined. I also could not find how ValueError works, but I’m guessing it fails if the input is not an integer?
EDIT 2: Oh, wait, it’s just a warning? Warnings can be ignored sometimes. Does the code compile and execute correctly? Your interface tries its best, and it sees a variable being defined inside a try statement, but it might not understand that the loop will prevent the failure.
Last edited by KillianHawkeye; 2020-12-01 at 01:13 PM.
-
2020-12-01, 06:23 PM (ISO 8601)
—
Top
—
End—
#4
Troll in the Playground
Re: Name can be Undefined (python3)
Originally Posted by KillianHawkeye
Your interface tries its best, and it sees a variable being defined inside a try statement, but it might not understand that the loop will prevent the failure.
That’s pretty much it.
Dice comes in with a value, it’s okay.
mod_bonus isn’t, and is in the try loop to keep people from giving an erroneous input. It breaks the try on a successful conversion to integer.
Oh, and check the mod_penalty loop. The condition is always true, there’s no break.
May you get EXACTLY what you wish for.
-
2020-12-01, 06:57 PM (ISO 8601)
—
Top
—
End—
#5
Barbarian in the Playground
Re: Name can be Undefined (python3)
Originally Posted by sihnfahl
That’s pretty much it.
Dice comes in with a value, it’s okay.
mod_bonus isn’t, and is in the try loop to keep people from giving an erroneous input. It breaks the try on a successful conversion to integer.
Oh, and check the mod_penalty loop. The condition is always true, there’s no break.
I think there is, there’s a comment in the middle of the loop, and after the comment it only unindents the try-except.
I don’t like something about the loop structure. Somehow it all looks a bit backwards. I’m not sure how to I would like it, and can’t think of an easy way to avoid it.
One possible possibility would be putting that section into it’s own function «inputint», that way you can forget about it in it’s code, (and it might be easier for the checker to work out what’s going on). but I’m not sure it’s any clearer.
In any case the way you did it made you think about how loops and trys work.Code:
def input_int(message): while true: try: return int(input(message)) modBonus=input_int(" ...") modPenalty=input_int("...") ...
Last edited by jayem; 2020-12-01 at 06:58 PM.
-
2020-12-01, 07:53 PM (ISO 8601)
—
Top
—
End—
#6
Troll in the Playground
Re: Name can be Undefined (python3)
Originally Posted by jayem
I think there is, there’s a comment in the middle of the loop, and after the comment it only unindents the try-except.
I think that was what was throwing me; the indentation. Still not 100% on python.
Cause in my mind, the penalty code would be the same as the modifier, in that it wouldn’t proceed until a valid number was entered.
so somewhere between …
Code:
while True: try: mod_penalty = int(input("Input Penalty")) final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier)) break except ValueError: continue
and
Code:
while True: try: mod_penalty = int(input("Input Penalty")) break except ValueError: continue final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier))
May you get EXACTLY what you wish for.
-
2020-12-02, 07:38 AM (ISO 8601)
—
Top
—
End—
#7
Troll in the Playground
Re: Name can be Undefined (python3)
Originally Posted by sihnfahl
I think that was what was throwing me; the indentation. Still not 100% on python.
Cause in my mind, the penalty code would be the same as the modifier, in that it wouldn’t proceed until a valid number was entered.
so somewhere between …
Code:
while True: try: mod_penalty = int(input("Input Penalty")) final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier)) break except ValueError: continue
and
Code:
while True: try: mod_penalty = int(input("Input Penalty")) break except ValueError: continue final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier))
I think you are right, since as it is I think the loop will print out the results even on a failed mod_penalty input try and break the loop without trying again.
In a war it doesn’t matter who’s right, only who’s left.
-
2020-12-02, 05:15 PM (ISO 8601)
—
Top
—
End—
#8
Barbarian in the Playground
Re: Name can be Undefined (python3)
Originally Posted by Radar
I think you are right, since as it is I think the loop will print out the results even on a failed mod_penalty input try and break the loop without trying again.
The «continue» (IIUC) should restart the while loop (if there is an invalid entry), so if the input is invalid it doesn’t reach the break
Personally, I find either of sihnfahl’s much easier to follow. When you get the «final_modifier = …», in the initial code you are having to take into account the While, Try, Except, Break & Continue all ‘interacting’ with the program flow. Also, as a bonus, it’s possibly easier for PyCharm to know what’s going on for the same reasons.
But at the middle of the day, if it works it works.
-
2020-12-02, 06:31 PM (ISO 8601)
—
Top
—
End—
#9
Troll in the Playground
Re: Name can be Undefined (python3)
Originally Posted by jayem
The «continue» (IIUC) should restart the while loop (if there is an invalid entry), so if the input is invalid it doesn’t reach the break
Personally, I find either of sihnfahl’s much easier to follow. When you get the «final_modifier = …», in the initial code you are having to take into account the While, Try, Except, Break & Continue all ‘interacting’ with the program flow. Also, as a bonus, it’s possibly easier for PyCharm to know what’s going on for the same reasons.
True, I misinterpreted the continue.
Originally Posted by jayem
But at the middle of the day, if it works it works.
This… I am not so sure anymore. Writing a given piece of code is rarely a one time work. You or someone else will have to revisit it at some point. Any unclear structure or an «ugly but working» quick-fix will always come back to bite you. Also, debugging becomes that much more difficult.
It might look innocent at the beginning, but…
In a war it doesn’t matter who’s right, only who’s left.
-
2020-12-02, 07:43 PM (ISO 8601)
—
Top
—
End—
#10
Titan in the Playground
Re: Name can be Undefined (python3)
Originally Posted by Radar
Writing a given piece of code is rarely a one time work. You or someone else will have to revisit it at some point. Any unclear structure or an «ugly but working» quick-fix will always come back to bite you. Also, debugging becomes that much more difficult.
Truth.
Hacking together an ugly code to get it to run only works in the short term. It’s better to learn to write code that will be readable and understandable when you look at it again six months or a year down the road. Code you can read is code you can debug, after all.
In addition to making things easier on your future self, establishing good habits when you’re doing small indie programming projects will help you immensely if you ever get into doing programming collaboratively.
-
2020-12-03, 12:26 AM (ISO 8601)
—
Top
—
End—
#11
Ettin in the Playground
Re: Name can be Undefined (python3)
Originally Posted by KillianHawkeye
Truth.
Hacking together an ugly code to get it to run only works in the short term. It’s better to learn to write code that will be readable and understandable when you look at it again six months or a year down the road. Code you can read is code you can debug, after all.
In addition to making things easier on your future self, establishing good habits when you’re doing small indie programming projects will help you immensely if you ever get into doing programming collaboratively.
Very truth.
The bane of your programming existence, should you choose to go past the minor hobbyist level, will be undocumented hacks that work «well enough» for the original author. Especially the ones in the half documented, not-fully-implemented, that-function-is-just-a-placeholder APIs from major commercial corporations.[/rant]
-
2020-12-03, 06:55 PM (ISO 8601)
—
Top
—
End—
#12
Bugbear in the Playground
Re: Name can be Undefined (python3)
Originally Posted by KillianHawkeye
Also, you should check your math or your input of of mod_penalty to see if the user enters a positive or negative number. I would expect to put in a negative number for a penalty, but then you’re subtracting it when you do the math part (a double negative). Easiest fix is to subtract the absolute value of mod_penalty using abs(mod_penalty).
I could try some of these ideas. My original idea was to use subtraction rather than adding a negative number because, input wise, the non-negative number is slightly faster to type. I am far from mathematically inclined but on looking it up I think I can make mod_penalty run off of absolute value so it accepts positive and negive numbers with the current system, That’s something at the very least.
Originally Posted by KillianHawkeye
EDIT: Alright, I’m not a Python expert. I noticed the extra while loops and you might be correct that the first try should repeat until it succeeds. In that case, I’m not sure how the variable could be undefined. I also could not find how ValueError works, but I’m guessing it fails if the input is not an integer?
Yes.
Originally Posted by KillianHawkeye
EDIT 2: Oh, wait, it’s just a warning? Warnings can be ignored sometimes. Does the code compile and execute correctly? Your interface tries its best, and it sees a variable being defined inside a try statement, but it might not understand that the loop will prevent the failure.
I assumed that it wasn’t something significant, I’m just going by the thought that if it’s considered worth mentioning I best look into it before there works out being some background oddity that can mess something up in the future. The code itself does what I want it to.
Originally Posted by sihnfahl
Oh, and check the mod_penalty loop. The condition is always true, there’s no break.
Honestly that’s a bit that confuses me. I had the break there at first but the code was not working as intended, I removed it on a gut feeling and it started behaving as I wanted and the loop has no issues.
Originally Posted by sihnfahl
I think that was what was throwing me; the indentation. Still not 100% on python.
Cause in my mind, the penalty code would be the same as the modifier, in that it wouldn’t proceed until a valid number was entered.
so somewhere between …
Code:
while True: try: mod_penalty = int(input("Input Penalty")) final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier)) break except ValueError: continue
and
Code:
while True: try: mod_penalty = int(input("Input Penalty")) break except ValueError: continue final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier))
After a quick try both of these have the same results. The warning now highlights both mod_bonus and mod_penalty and code function does not appear noticeably changed.
Originally Posted by jayem
One possible possibility would be putting that section into it’s own function «inputint», that way you can forget about it in it’s code, (and it might be easier for the checker to work out what’s going on). but I’m not sure it’s any clearer.
In any case the way you did it made you think about how loops and trys work.Code:
def input_int(message): while true: try: return int(input(message)) modBonus=input_int(" ...") modPenalty=input_int("...") ...
I considered something like this early on actually. I ‘ll try it out once I’ve more time.
Edit:
If nothing else, I got my original bit of code to stop showing the warning.Spoiler
Show
Code:
mod_bonus = 0 mod_penalty = 0 # Takes result of dice roll and then offers to apply a further modifier. while True: apply_mod = input("Apply Modifier? yes/no") if apply_mod == "yes": # finds bonus while True: try: mod_bonus = int(input("Input Bonus")) break except ValueError: continue # finds penalty while True: try: mod_penalty = int(input("Input Penalty")) break except ValueError: continue # finds modifier and adds to prior roll final_modifier = int(dice + mod_bonus - mod_penalty) print("Modified roll is: " + str(final_modifier)) elif apply_mod == "no": print("Random Selected Number is: " + str(dice)) break
Meanwhile I’ve been playing around with functions and gotten to this:
Spoiler
Show
Code:
# collects and applys bonus and penalty to apply to dice roll def dice_ajst(): while True: try: add_this = int(input("Input Bonus")) sub_input = input("Input Penalty") sub_this = int(sub_input) final = dice + add_this + sub_this print(final) break except ValueError: continue dice_ajst()
which has lead me to the WIP version three of the code where I want it to have the same effect as the loops in v1 but be concise and readable like v2.
Last edited by ThreadNecro5; 2020-12-08 at 03:22 PM.

Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
- BB code is On
- Smilies are On
- [IMG] code is On
- [VIDEO] code is On
- HTML code is Off
Forum Rules
Go to pycharm
r/pycharm
r/pycharm
Subreddit for JetBrains PyCharm, the Python IDE for professional developers by JetBrains.
Find out more about PyCharm at https://www.jetbrains.com/pycharm/
Members
Online
•
by
guitar995
Name can be undefined error
Hello all,
I’m new to python and I keep getting a ‘name can be undefined error’ it doesn’t seem to effect anything.
I’m just wondering how I can fix the error? Thanks
NameError — одна из самых распространенных ошибок в Python. Начинающих она может пугать, но в ней нет ничего сложного. Это ошибка говорит о том, что вы попробовали использовать переменную, которой не существует.
В этом руководстве поговорим об ошибке «NameError name is not defined». Разберем несколько примеров и разберемся, как эту ошибку решать.
NameError возникает в тех случаях, когда вы пытаетесь использовать несуществующие имя переменной или функции.
В Python код запускается сверху вниз. Это значит, что переменную нельзя объявить уже после того, как она была использована. Python просто не будет знать о ее существовании.
Самая распространенная NameError
выглядит вот так:
NameError: name 'some_name' is not defined
Разберем частые причина возникновения этой ошибки.
Причина №1: ошибка в написании имени переменной или функции
Для человека достаточно просто сделать опечатку. Также просто для него — найти ее. Но это не настолько просто для Python.
Язык способен интерпретировать только те имена, которые были введены корректно. Именно поэтому важно следить за правильностью ввода всех имен в коде.
Если ошибку не исправить, то возникнет исключение. Возьмем в качестве примера следующий код:
books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
print(boooks)
Он вернет:
Traceback (most recent call last):
File "main.py", line 3, in
print(boooks)
NameError: name 'boooks' is not defined
Для решения проблемы опечатку нужно исправить. Если ввести print(books)
, то код вернет список книг.
Таким образом при возникновении ошибки с именем в первую очередь нужно проверить, что все имена переменных и функций введены верно.
Причина №2: вызов функции до объявления
Функции должны использоваться после объявления по аналогии с переменными. Это связано с тем, что Python читает код сверху вниз.
Напишем программу, которая вызывает функцию до объявления:
books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
print_books(books)
def print_books(books):
for b in books:
print(b)
Код вернет:
Traceback (most recent call last):
File "main.py", line 3, in
print_books(books)
NameError: name 'print_books' is not defined
На 3 строке мы пытаемся вызвать print_books()
. Однако эта функция объявляется позже.
Чтобы исправить эту ошибку, нужно перенести функцию выше:
def print_books(books):
for b in books:
print(b)
books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
print_books(books)
Причина №3: переменная не объявлена
Программы становятся больше, и порой легко забыть определить переменную. В таком случае возникнет ошибка. Причина в том, что Python не способен работать с необъявленными переменными.
Посмотрим на программу, которая выводит список книг:
Такой код вернет:
Traceback (most recent call last):
File "main.py", line 1, in
for b in books:
NameError: name 'books' is not defined
Переменная books
объявлена не была.
Для решения проблемы переменную нужно объявить в коде:
books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
for b in books:
print(b)
Причина №4: попытка вывести одно слово
Чтобы вывести одно слово, нужно заключить его в двойные скобки. Таким образом мы сообщаем Python, что это строка. Если этого не сделать, язык будет считать, что это часть программы. Рассмотрим такую инструкцию print()
:
Этот код пытается вывести слово «Books» в консоль. Вместо этого он вернет ошибку:
Traceback (most recent call last):
File "main.py", line 1, in
print(Books)
NameError: name 'Books' is not defined
Python воспринимает «Books» как имя переменной. Для решения проблемы нужно заключить имя в скобки:
Теперь Python знает, что нужно вывести в консоли строку, и код возвращает Books
.
Причина №5: объявление переменной вне области видимости
Есть две области видимости переменных: локальная и глобальная. Локальные переменные доступны внутри функций или классов, где они были объявлены. Глобальные переменные доступны во всей программе.
Если попытаться получить доступ к локальной переменной вне ее области видимости, то возникнет ошибка.
Следующий код пытается вывести список книг вместе с их общим количеством:
def print_books():
books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
for b in books:
print(b)
print(len(books))
Код возвращает:
Traceback (most recent call last):
File "main.py", line 5, in
print(len(books))
NameError: name 'books' is not defined
Переменная books
была объявлена, но она была объявлена внутри функции print_books()
. Это значит, что получить к ней доступ нельзя в остальной части программы.
Для решения этой проблемы нужно объявить переменную в глобальной области видимости:
books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
def print_books():
for b in books:
print(b)
print(len(books))
Код выводит название каждой книги из списка books
. После этого выводится общее количество книг в списке с помощью метода len()
.