1

I try to run this code and write "hello" but get en error:

Value = input("Type less than 6 characters: ")
LetterNum = 1
for Letter in Value: 
    print("Letter ", LetterNum, " is ", Letter)
    LetterNum+=1
    if LetterNum > 6:
        print("The string is too long!")
        break

get error:

>>> 
Type less than 6 characters: hello

Traceback (most recent call last):
  File "C:/Users/yaron.KAYAMOT/Desktop/forBreak.py", line 1, in <module>
    Value = input("Type less than 6 characters: ")
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
>>> 

i don't know why it don't work

newGIS
  • 598
  • 3
  • 10
  • 26
  • In Python 2.x, use `raw_input` – jonrsharpe Apr 16 '15 at 14:43
  • 2
    possible duplicate of ["NameError: name '' is not defined" after user input in Python](http://stackoverflow.com/questions/2090706/nameerror-name-is-not-defined-after-user-input-in-python) – jonrsharpe Apr 16 '15 at 14:43

2 Answers2

1

TL;DR: use raw_input()


That is because input() in Python 2.7 tries to evaluate your input (literally: hello is interpreted the same way as it will be written in your code):

>>> input("Type less than 6 characters: ")
Type less than 6 characters: 'hello'
'hello'

The word hello is parsed as variable, so input() complains the same way interpreter will do:

>>> hello
...
NameError: name 'hello' is not defined
>>> input()
hello
...
NameError: name 'hello' is not defined
>>> hello = 1
>>> hello
1
>>> input()
hello
1

Use raw_input() instead which returns raw string:

>>> raw_input("Type less than 6 characters: ")
Type less than 6 characters: hello
'hello'

This design flaw was fixed in Python 3.

myaut
  • 11,174
  • 2
  • 30
  • 62
1

You should use raw_input() instead of input().

according to document

input([prompt]) Equivalent to eval(raw_input(prompt)).

If input is some numbers,you may use 'input()'.But you should better never use 'input()',use 'int(raw_input())' instead.

Value = raw_input("Type less than 6 characters: ")
LetterNum = 1
for Letter in Value: 
    print("Letter ", LetterNum, " is ", Letter)
    LetterNum+=1
    if LetterNum > 6:
        print("The string is too long!")
        break

Type less than 7 characters: hello
('Letter ', 1, ' is ', 'h')
('Letter ', 2, ' is ', 'e')
('Letter ', 3, ' is ', 'l')
('Letter ', 4, ' is ', 'l')
('Letter ', 5, ' is ', 'o')
woodrat
  • 31
  • 3