是否可以将字符串与变量进行比较?

时间:2013-05-31 06:50:13

标签: python python-2.7

这段代码合法吗?

def ask_to_leave():
  if answer == 'y':
    return False
  elif answer == 'n':
    return True

我收到此错误:

    Traceback (most recent call last):
      File "MACROCALC.py", line 62, in <module>
        main()
      File "MACROCALC.py", line 17, in main
        answer = input("Are you done using the calculator?(y/n)")
      File "<string>", line 1, in <module>
    NameError: name 'y' is not defined

这是我的代码的链接

http://pastebin.com/EzqBi0KG

1 个答案:

答案 0 :(得分:8)

您在Python 2上使用input() function,它将输入解释为Python代码。请改用raw_input() function

answer = raw_input("Are you done using the calculator?(y/n)")

使用input()时,输入的文本将发送到eval(),其中需要有效的python表达式,y被视为变量名称:

>>> input('Enter a python expression: ')
Enter a python expression: 1 + 1
2
>>> input('Enter a python expression: ')
Enter a python expression: y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'y' is not defined
>>> input('Enter a python expression: ')
Enter a python expression: 'y'
'y'

请注意我必须使用引号输入'y' 才能使用它;文字Python字符串表达式。 raw_input()没有此类限制:

>>> raw_input('Enter the second-last letter of the alphabet: ')
Enter the second-last letter of the alphabet: y
'y'