Nameerror name word is not defined

I’m trying to write a Pig latin translator and have run into the following error:

line 37, in <module>
    for i in word:
NameError: name 'word' is not defined

when I try to run this program.

Here is the relevant code:

def Pig_word0 (word): 
    "" "This is a function which can make string translate to pig latin and first letter become capital." "" 
# Determined string include a, e, i, o, u or not 
Prefix = [] 
for i in word: 
    if i in "aeiouy":
        break 
else: 
    Prefix.append (i) 

Any tips appreciated. Thanks.

Andy's user avatar

Andy

48.5k58 gold badges167 silver badges230 bronze badges

asked Jun 30, 2015 at 15:40

Shane McGriever's user avatar

5

the problem here is, the interpreter assuming your code as two separate blocks

1) def Pig_word0 (word):
«» «This is a function which can make string translate to pig latin and first letter become capital.» «»

2)

# Determined string include a, e, i, o, u or not <br/>
  Prefix = [] 
  for i in word: 
      if i in "aeiou":
          break 
      else: 
          Prefix.append (i) 

so, properly indent the code and check

answered Jun 30, 2015 at 15:55

shravan cherukuri's user avatar

0

I’m trying to make a mixWord function and I’m getting an error saying
NameError: name 'word' is not defined
What am I missing from here?

def mixWord(word):
    characterList = list(word);
    print characterList
    import random;
    random.shuffle(characterList);
    print characterList;
    shuffledWord = ''.join(characterList);
    print shuffledWord;

Traceback (most recent call last):

File «», line 1, in

mixWord (word)

NameError: name ‘word’ is not defined

BlitZ's user avatar

BlitZ

11.9k3 gold badges51 silver badges67 bronze badges

asked Jun 21, 2013 at 4:00

user2510694's user avatar

16

The problem is PEBKAC — exactly what form, is for you to find out.

That is, the code executed is not the same as the code posted; the posted code works as expected:

def mixWord(word):
    characterList = list(word);
    print characterList
    import random;
    random.shuffle(characterList);
    print characterList;
    shuffledWord = ''.join(characterList);
    print shuffledWord;

mixWord("PEBKAC")

So, find out why:

  • Has the file been saved?
  • Has the file been saved to the correct location?
  • Is the file from the correct location being run?
  • Is the error from different code entirely?

Also try running the code directly from an IDLE buffer as that should be immune to the previous potential issue(s).

After resolving the issue, consider updating the code to not using semicolons as they are not required here and it is un-Pythonic.

answered Jun 21, 2013 at 4:26

user2246674's user avatar

user2246674user2246674

7,62125 silver badges28 bronze badges

I think the problem is that you are calling mixWord(word) without defining any word variable.

answered Jun 21, 2013 at 4:12

Ankur Ankan's user avatar

Ankur AnkanAnkur Ankan

2,8882 gold badges22 silver badges38 bronze badges

5

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().

Первый шаг в исправлении ошибок при написании кода — понять, что именно пошло не так. И хотя некоторые сообщения об ошибках могут показаться запутанными, большинство из них помогут вам понять, что же не работает в вашей программе. В этой статье мы поговорим о том, как исправить ошибку NameError в Python. Мы рассмотрим несколько примеров кода, показывающих, как и почему возникает эта ошибка, и покажем, как ее исправить.

В Python ошибка NameError возникает, когда вы пытаетесь использовать переменную, функцию или модуль, которые не существуют, или использовать их недопустимым образом.

Некоторые из распространенных причин, вызывающих эту ошибку:

  • Использование имени переменной или функции, которое еще не определено
  • Неправильное написание имени переменной/функции при её вызове
  • Использование модуля в Python без импорта этого модуля и т. д.

Как исправить «NameError: Name Is Not Defined» в Python

В этом разделе мы рассмотрим, как исправить ошибку NameError: Name is Not Defined в Python.

Мы начнем с блоков кода, вызывающих ошибку, а затем посмотрим, как их исправить.

[python_ad_block]

Пример №1. Имя переменной не определено

name = "John"

print(age)
# NameError: name 'age' is not defined

В приведенном выше коде мы определили переменную name, но далее попытались вывести переменную age, которая ещё не была определена.

Мы получили сообщение об ошибке: NameError: name 'age' is not defined. Это означает, что переменная age не существует, мы её не задали.

Чтобы исправить это, мы можем создать переменную, и наш код будет работать нормально. К примеру, это можно сделать следующим образом:

name = "John"
age = 12

print(age)
# 12

Теперь значение переменной age выводится без проблем.

Точно так же эта ошибка может возникнуть, если мы неправильно напишем имя нашей переменной. Например, сделаем так:

name = "John"

print(nam)
# NameError: name 'nam' is not defined

В коде выше мы написали nam вместо name. Чтобы исправить подобную ошибку, вам просто нужно правильно написать имя вашей переменной.

Пример №2. Имя функции не определено

def sayHello():
    print("Hello World!")
    
sayHelloo()
# NameError: name 'sayHelloo' is not defined

В приведенном выше примере мы добавили лишнюю букву o при вызове функции — sayHelloo() вместо sayHello(). Это просто опечатка, однако она вызовет ошибку, потому что функции с таким именем не существует.

Итак, мы получили ошибку: NameError: name 'sayHelloo' is not defined. Подобные орфографические ошибки очень легко пропустить. Сообщение об ошибке обычно помогает исправить это.

Вот правильный способ вызова данной функции:

def sayHello():
    print("Hello World!")
    
sayHello()
# Hello World!

Как мы видели в предыдущем разделе, вызов переменной, которая еще не определена, вызывает ошибку. То же самое относится и к функциям.

К примеру, это может выглядеть так:

def sayHello():
    print("Hello World!")
    
sayHello()
# Hello World!

addTWoNumbers()
# NameError: name 'addTWoNumbers' is not defined

В приведенном выше коде мы вызвали функцию addTWoNumbers(), которая еще не была определена в программе. Чтобы исправить это, вы можете создать функцию, если она вам нужна, или просто избавиться от нее.

Обратите внимание, что вызов функции перед ее созданием приведет к той же ошибке. То есть такой код также выдаст вам ошибку:

sayHello()

def sayHello():
    print("Hello World!")
    
# NameError: name 'sayHello' is not defined

Поэтому вы всегда должны определять свои функции перед их вызовом.

Пример №3. Использование модуля без его импорта

x = 5.5

print(math.ceil(x))
# NameError: name 'math' is not defined

В приведенном выше примере мы используем метод математической библиотеки Python math.ceil(). Однако до этого мы не импортировали модуль math.

В результате возникает следующая ошибка: NameError: name 'math' is not defined. Это произошло потому, что интерпретатор не распознал ключевое слово math.

Таким образом, если мы хотим использовать функции библиотеки math в Python, мы должны сначала импортировать соответствующий модуль.

Вот так будет выглядеть исправленный код:

import math

x = 5.5

print(math.ceil(x))
# 6

В первой строке кода мы импортировали математический модуль math. Теперь, когда вы запустите приведенный выше код, вы получите результат 6. То же самое относится и ко всем остальным библиотекам. Сначала нужно импортировать библиотеку с помощью ключевого слова import, а потом уже можно использовать весь функционал этой библиотеки. Подробнее про импорт модулей можно узнать в статье «Как импортировать в Python?»

Заключение

В этой статье мы поговорили о том, как исправить ошибку NameError в Python.

Мы выяснили, что собой представляет NameError. Затем мы разобрали несколько примеров, которые могли вызвать ошибку NameError при работе с переменными, функциями и модулями в Python. Также мы показали, как можно исправить эти ошибки.

Надеемся, данная статья была вам полезна! Успехов в написании кода!

Перевод статьи «NameError: Name plot_cases_simple is Not Defined – How to Fix this Python Error».

NameErrors are one of the most common types of Python errors. When you’re first getting started, these errors can seem intimidating. They’re not too complicated. A NameError means that you’ve tried to use a variable that does not yet exist.

In this guide, we’re going to talk about the “nameerror name is not defined” error and why it is raised. We’ll walk through a few example solutions to this error to help you understand how to resolve it in your code.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

What is a NameError?

A NameError is raised when you try to use a variable or a function name that is not valid.

In Python, code runs from top to bottom. This means that you cannot declare a variable after you try to use it in your code. Python would not know what you wanted the variable to do.

The most common NameError looks like this:

nameerror name is not defined

Let’s analyze a few causes of this error.

Cause #1: Misspelled Variable or Function Name

It’s easy for humans to gloss over spelling mistakes. We can easily tell what a word is supposed to be even if it is misspelled. Python does not have this capability.

Python can only interpret names that you have spelled correctly. This is because when you declare a variable or a function, Python stores the value with the exact name you have declared.

If there is a typo anywhere that you try to reference that variable, an error will be returned.

Consider the following code snippet:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print(boooks)

Our code returns:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	print(boooks)
NameError: name 'boooks' is not defined

To solve this problem, all we have to do is fix the typo. If we use “print(books)”, our code returns:

["Near Dark", "The Order", "Where the Crawdads Sing"]

If you receive a name error, you should first check to make sure that you have spelled the variable or function name correctly.

Cause #2: Calling a Function Before Declaration

Functions must be declared before they are used, like variables. This is because Python reads code from top-to-bottom. 

Let’s write a program that calls a function before it is declared:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print_books(books)

def print_books(books):
	for b in books:
		print(b)

Our code returns:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	print_books(books)
NameError: name 'print_books' is not defined

We are trying to call print_books() on line three. However, we do not define this function until later in our program. To fix this error, we can move our function declaration to a place before we use it:

def print_books(books):
	for b in books:
		print(b)

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

print_books(books)

Our code returns:

Near Dark
The Order
Where the Crawdads Sing

Our code has successfully printed out the list of books.

Cause #3: Forget to Define a Variable

As programs get larger, it is easy to forget to define a variable. If you do, a name error is raised. This is because Python cannot work with variables until they are declared.

Let’s take a look at a program that prints out a list of books:

Our code returns: 

Traceback (most recent call last):
  File "main.py", line 1, in <module>
	for b in books:
NameError: name 'books' is not defined

We have not declared a variable called “books”. To solve this problem, we need to declare “books” before we use it in our code:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

for b in books:
print(b)

Let’s try to run our program again and see what happens:

Near Dark
The Order
Where the Crawdads Sing

Now that we have defined a list of books, Python can print out each book from the list.

Cause #4: Try to Print a Single Word

To print out a word in Python, you need to surround it in either single or double quotes. This tells Python that a word is a string. If a word is not surrounded by quotes, it is treated as part of a program. Consider the following print() statement:

This code tries to print the word “Books” to the console. The code returns an error:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Traceback (most recent call last):
  File "main.py", line 1, in <module>
	print(Books)
NameError: name 'Books' is not defined

Python treats “Books” like a variable name. To solve this error, we can enclose the word “Books” in quotation marks:

Python now knows that we want to print out a string to the console. Our new code returns: Books.

Cause #5: Declaring a Variable Out of Scope

There are two variable scopes: local and global.

Local variables are only accessible in the function or class in which they are declared. Global variables are accessible throughout a program.

If you try to access a local variable outside the scope in which it is defined, an error is raised.

The following code should print out a list of books followed by the number of books in the list:

def print_books():
  books = ["Near Dark", "The Order", "Where the Crawdads Sing"]
  for b in books:
      print(b)

print_books()
print(len(books))

Our code returns:

Near Dark
The Order
Where the Crawdads Sing
Traceback (most recent call last):
  File "main.py", line 6, in <module>
	print(len(books))
NameError: name 'books' is not defined

Our code successfully prints out the list of books. On the last line of our code, an error is returned. While we have declared the variable “books”, we only declared it inside our print_books() function. This means the variable is not accessible to the rest of our program.

To solve this problem, we can declare books in our main program. This will make it a global variable:

books = ["Near Dark", "The Order", "Where the Crawdads Sing"]

def print_books():
  for b in books:
      print(b)

print_books()
print(len(books))

Our code returns:

Near Dark
The Order
Where the Crawdads Sing
3

Our code prints out every book in the “books” list. Then, our code prints out the number of books in the list using the len() method.

Понравилась статья? Поделить с друзьями:
  • Named ranges excel как
  • Named range in word
  • Name yourself in one word
  • Name word search puzzles
  • Name word meaning dictionary