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

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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')

2 Comments

"input() is for numbers" - not really. You should pretty much never use it.
It's my fault. my english is not very good. "input() is for numbers" is not precisely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.