Python输入法标签在打印时给出错误

时间:2019-04-24 17:18:20

标签: python

我正在独自练习python,并努力使用输入法。我的程序如下

a = (input('Enter any alphabet: '))
print 'type is: ',a
if a=='a':
    print 'The given character is vowel a '
elif a=='e':
    print 'The given character is vowel e'
elif a=='i':
    print 'The given character is vowel i'
elif a=='o':
    print 'The given character is vowel o'
elif a=='u':
    print 'The given character is vowel u'
else:
   print 'The give character is a consonent'
print "Thats all folks"

我输入如下所示的一位数字字母时出现错误

Enter any alphabet: a
Traceback (most recent call last):
File "Demo_if_ladder.py", line 1, in <module>
a = input('Enter any alphabet: ')
File "<string>", line 1, in <module>
NameError: name 'a' is not defined

为什么会发生这种情况,如果我以单引号形式输入一位数字字母但不接受没有单引号的一位数字字母,则该程序可以正常工作

2 个答案:

答案 0 :(得分:1)

似乎您正在从print语句语法运行python 2。 在python 2中,input(...)试图像执行命令一样运行内容。因此,当您输入内容时,python将尝试执行它。

您的问题的解决方案是改用raw_input(...),它会返回一个字符串。

答案 1 :(得分:0)

您正在使用Python 2。

在Python 2中,输入接受Python命令。您可以使用raw_input获得所需的效果。

单引号解决了此问题,因为Python命令中的文本用单引号书写。

如果运行以下命令,您会清楚地了解

a = (input('please, write: "list(range(10))"\n'))
print a
a = raw_input('please, write: "list(range(10))"\n')
print a

在Python 3中,输入可以按预期工作,但是将print语句更改为函数。在Python 3中,您应该更改

print a

print(a)
相关问题