-1

这段代码合法吗?

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

4

1 回答 1

8

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

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'
于 2013-05-31T06:58:39.653 回答