Error entering data with input ()

3

This is my code, which I run in Python 2.7.13:

print "hola"
hiola = input()
if hiola == salsa:
    print "hola"

And the error that throws me is the following:

Traceback (most recent call last):
  File "C:\Programacion\Python\hola.py", line 2, in <module>
    hiola = input()
  File "<string>", line 1, in <module>
NameError: name 'salsa' is not defined
    
asked by SENIORofPRESTON 354 17.05.2017 в 21:03
source

1 answer

4

The problem is that you are using input under python 2.7 as you would in Python 3. input expects valid Python code which evaluates, if you enter hola or another string without using quotation marks ( "hola" ), interprets it as an identifier, as a variable, and as it is not defined in the namespace , throw the exception shown.

To do what you want in Python 2.x you must use raw_input that returns always a string:

print "hola"
hiola = raw_input()
if hiola == 'salsa':
    print "hola"

On the other hand, do not enter quotation marks salsa , if it is a variable you must define it before, for example:

salsa = 'hola'

if salsa is not a variable and it is a literal string you should put it in quotation marks:

if hiola == 'salsa':

To see the differences between input and raw_input (and the differences about Python 3 and Python 2) you can look at this question:

answered by 17.05.2017 / 21:16
source