Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python input() not working as expected [duplicate]

Tags:

python

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
like image 830
liv2hak Avatar asked Jan 21 '14 06:01

liv2hak


People also ask

Why input function is not working in Python?

This function was known by the name of raw_input earlier in Python 2. It was later changed to a much simpler name 'input' in Python 3. The raw_input function is obsolete in Python 3 which means, if you are using the latest version of Python then you will not be able to use it.

What does int input ()) mean in Python?

With int(input()) you're casting the return value of the input() function call to an integer. With input(int()) you're using int() as a prompt for the user input. Since you don't pass int() an argument, it returns zero.

How do you continue asking for input in Python?

To ask for user input in Python, use the built-in input() function. In addition to asking for simple string input like this, you also want to learn how to: Ask for multiple inputs in one go. Ask for input again until valid input is given.

How do you make a code repeat itself in Python?

Use range() to print a string multiple times Use range(stop) to create a range of 0 to stop where stop is the number of lines desired. Use a for-loop to iterate through this range. In each iteration, concatenate the string to itself by the number of times desired and print the result.


1 Answers

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.

like image 185
Christian Tapia Avatar answered Sep 19 '22 19:09

Christian Tapia