Nameerror: name 'ana' is not defined

Asked

Viewed 1,425 times

7

I am a beginner in python and I needed to make a program that would verify if a given word is palindromo. The program then would be:

#encoding: utf-8

palavra = input ('Palavra: ')
if palavra == palavra[::-1]:
   print ("%s é palindrome" %palavra)
else:
   print ("%s não é palindrome" %palavra)

The problem is that when I try to open the program from the terminal (use Ubuntu 16.04), the following error appears:

Traceback (most recent call last):
  File "palindrome.py", line 3, in <module>
    palavra = input ('Palavra: ')
  File "<string>", line 1, in <module>
NameError: name 'ana' is not defined

And I have no idea what that means. This has happened whenever I need to work as string variables in python, someone knows why it happens?

2 answers

7


It turns out that you are trying to execute code made for Python 3.* using Python 2.*. Swap input for raw_input that will work.

You will probably need to change the comments to be able to use the accents.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

palavra = raw_input ('Palavra: ')
if palavra == palavra[::-1]:
   print ("%s é palindrome" %palavra)
else:
   print ("%s não é palindrome" %palavra)

input() Python 2.* takes the value typed by the user and tries to "evaluate" it (it’s like trying to interpret the string as code itself). It’s the same thing as doing eval(raw_input()).

In Python 3.*, the input() does the same as the old raw_input.

  • 1

    the way he declared the text encoding of the Python file (#encoding: utf-8) works too. No need to put the -*- - they are only present in many examples and documents because in this way the coding was also recognized by older versions of EMACS.

  • 1

    Thanks for the @jsbueno add-on. I didn’t know it worked the other way because I always see it the way I did...

  • 1

    It uses a regular expression, and looks for coding: codifição on the first or second line, with or without spaces after two dots. In Python3 it is assumed that the encoding is utf-8, making the line unnecessary.

3

I believe you wish to use the function raw_input, in fact the function input in python version 2.7 works a different way, see an example:

>>> d="eder"
>>> palavra = input("teste:")
teste:d
>>> palavra
'eder'

He expects something python can interpret in the code, in this case I had declared the variable d getting my name.

let’s test the function raw_input now:

>>> palavra = raw_input('Palavra: ')
Palavra: eder
>>> palavra
'eder'

Therefore raw_input seems to be what you need...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.