For循环和If condition-python

时间:2015-04-16 14:36:43

标签: python-2.7

我尝试运行此代码并编写" hello"但得到错误:

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

得到错误:

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

我不知道为什么它不起作用

2 个答案:

答案 0 :(得分:1)

TL; DR :使用raw_input()


这是因为Python 2.7中的input()尝试evaluate您的输入(字面意思:hello的解释方式与在代码中编写的方式相同):

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

单词hello被解析为变量,因此input()抱怨解释器将采用相同的方式:

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

使用raw_input()代替返回原始字符串:

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

此设计缺陷已在Python 3中修复。

答案 1 :(得分:1)

您应该使用 raw_input()而不是input()。

根据document

input([prompt])相当于eval(raw_input(prompt))。

如果输入是某些数字,您可以使用&#39;输入()&#39;。但最好不要使用&#39;输入()&#39;,使用&#39; int(raw_input ())&#39;代替。

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