newGIS
newGIS

Reputation: 618

For loop and If condition- python

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

Upvotes: 1

Views: 115

Answers (2)

woodrat
woodrat

Reputation: 31

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

Upvotes: 1

myaut
myaut

Reputation: 11494

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.

Upvotes: 1

Related Questions