Python problem with input

Hello everyone,

I have just started python, and there is something that escapes me. I don't understand why my little script doesn't work.

When I do, it work:

my_string = "bonjour"

if len(my_string) < "6":
        print(my_string + " < 6")
else:
        print(my_string + " > 6")

But when I do, It doesn't work, why ?!

my_string = input(": ")
my_string = str(my_string)

if len(my_string) < "6":
        print(my_string + " < 6")
else:
        print(my_string + " > 6")

output:

Traceback (most recent call last):
  File "./test.py", line 6, in <module>
    my_string = input(" :")
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

Thanks by advance..

Please mention the Python version you're using.
Since the difference between your two programs is the "input()" function, it should be clear that the "input()" function is the problem.

From your error message, I assume you are using Python 2.
In Python 2, "input()" function tries to evaluate the expression you enter at the prompt. Check the documentation here:
25.4. 2to3 - Automated Python 2 to 3 code translation � Python 2.7.13 documentation

So, when you enter "hello" at the prompt, Python tries to evaluate it and throws an error since it is an undefined identifier.

$
$ cat -n test.py
     1  my_string = input(": ")
     2  my_string = str(my_string)
     3
     4  if len(my_string) < "6":
     5      print(my_string + " < 6")
     6  else:
     7      print(my_string + " > 6")
     8
$
$ python --version
Python 2.5.1
$
$ python ./test.py
: hello
Traceback (most recent call last):
  File "./test.py", line 1, in <module>
    my_string = input(": ")
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
$
$

If you really want to use the "input()" function, enter an expression that could be evaluated by "eval()" and you will not see the error message.

$
$ python ./test.py
: 2 + 3
5 < 6
$
$

In the above execution, I entered "2 + 3" which was evaluated by "eval()" to obtain 5. That was converted to string and assigned to "my_string" and then the comparison works.

In case you want to enter a string value like "hello", use "raw_input()" function in Python 2.
Check the documentation here:
2. Built-in Functions � Python 2.7.13 documentation

$
$ cat -n test.py
     1  my_string = raw_input(": ")
     2  my_string = str(my_string)
     3
     4  if len(my_string) < "6":
     5      print(my_string + " < 6")
     6  else:
     7      print(my_string + " > 6")
     8
$
$ python --version
Python 2.5.1
$
$ python ./test.py
: hello
hello < 6
$
$
1 Like

Thanks for your reply, my version is Python 2.7.6,

my_string = raw_input(": ")

It work for me :slight_smile: