NameError: 名称 '\[string\]' 未定义

新手上路,请多包涵

在测试我的程序时,我不断收到此错误:

 1. Encrypt a file
2. Decrypt a file
----> 1
Enter the filename you'd like to encrypt: test
Traceback (most recent call last):
  File "./encrypt.py", line 71, in <module>
    Main()
  File "./encrypt.py", line 58, in Main
    filename = input("Enter the filename you'd like to encrypt: ")
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

这是我的 Main() 函数代码:

 def Main():
        print("1. Encrypt a file")
        print("2. Decrypt a file")
        choice = str(input("----> "))
        if choice == '1':
                filename = input("Enter the filename you'd like to encrypt: ")
                password = input("Enter a password used for the encryption tool: ")
                encrypt(getKey(password), filename)
                print("File has been encrypted.")
        elif choice == '2':
                filename = input("Enter the filename you'd like to decrypt: ")
                password = input("Enter the password used for the encryption of this file: ")
                decrypt(getKey(password), filename)
                print("File has been decrypted. Note that if the password used in the encryption does " \
            + "not match the password you entered in, the file will remain encrypted.")
        else:
                print("Invalid option. Closing the program...")

我正在使用简单的 input() 方法来获取我的数据(例如“测试”),并且它一直告诉我我在运行时输入的任何信息,我刚刚输入的名称没有定义。我没有看到任何格式错误、语法错误等。

原文由 CodyT96 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 450
1 个回答

您将要使用 raw_input() 而不是 input()input 尝试运行它作为 Python 表达式获得的表达式,而 raw_input 返回一个字符串。这是在 Python 2.x 中;在 3.x 中 raw_input 不存在。

当您获得 NameError 时,它试图将您的输入作为表达式运行,但是 test 不存在。

原文由 Peter Wang 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题