5
votes

I am a python newbie.I am getting familiar with loops and tried this example from a book

while True:
        s = input('Enter something : ')
        if s == 'quit':
                break
        print('Length of the string is', len(s))
print('Done')

However the output is as follows

Enter something : ljsdf
Traceback (most recent call last):
  File "trial_2.py", line 2, in <module>
    s = input('Enter something : ')
  File "<string>", line 1, in <module>
NameError: name 'ljsdf' is not defined
5
for what it's worth: This is essentially a duplicate of stackoverflow.com/q/11295325/748858 although you probably wouldn't be able to find it if you didn't know where to look ... - mgilson

5 Answers

10
votes

You have to use raw_input() instead (Python 2.x), because input() is equivalent to eval(raw_input()), so it parses and evaluates your input as a valid Python expression.

while True:
        s = raw_input('Enter something : ')
        if s == 'quit':
                break
        print('Length of the string is', len(s))
print('Done')

Note:

input() doesn't catch user errors (e.g. if user inputs some invalid Python expression). raw_input() can do this, because it converts the input to a string. For futher information, read Python docs.

4
votes

you want raw_input() in python2

while True:
    s = raw_input('Enter something : ')
    if s == 'quit':
            break
    print 'Length of the string is', len(s)
print 'Done'

input() tries to evaluate (dangerously!) what you give it

3
votes

Your code will work fine in python 3.x

But if you are using python 2 you will have to input string using raw_input()

while True:
    s = raw_input('Enter something : ')
    if s == 'quit':
        break
    print('Length of the string is', len(s))
print('Done')
2
votes

It seems like you're using Python 2.x, while the code is expected to be run in Python 3.x.

input in Python 2.x evaluates the input string unlike input in Python 3.x.

2
votes

In Python 2.x input() is designed to return numbers, int or float depending on the input from the user, you can also enter variable names.

you need to use:

raw_input('Enter something: ')

The error is caused because Python thinks that "ljsdf" is the name of a variable, and that's why it raises this exception:

NameError: name 'ljsdf' is not defined

becuase "ljsdf" is not defined as a variable. :D

raw_input() is safer to use, and then convert the input to whatever other type after :D