“NameError:name not defined”是什么意思?

时间:2017-02-11 17:42:20

标签: python

所以我一直致力于我的文本加密和解密程序,我被困住了。这就是我到目前为止所做的:

  import random
  def fileopen():
       filename=input("What is the file you need to encrypt:")
       print(filename)
       with open(filename) as wordfile:
             contents=wordfile.read()
       return contents
 def Create8():
      numlist=[]
      charlist=[]
      for i in range (8):
           num=random.randint(33,126)
           numlist.append(num)
 for i in numlist:
      char = chr(i)
      charlist.append(char)
      return charlist
 def offset(key):
  store=[]
  for i in key:
        num=ord(i)
        store.append(num)
  total=sum(store)
  oFactor=((total//8)-32)

  return oFactor



  while True:
       print ("Hello, welcome to the encryption/decryption program")
       print ("1 - Encryption")
       print ("2 - Decryption")
       print ("3 - Exit")
       choice=input ("Enter a Number")

  if choice=="1":
       print("Encryption Selected")

       contents=fileopen()
       print(contents)

       Characterkey=Create8()

        OF=offset(Characterkey)

        print ("The offset factor is:")
        print (OF)

        Etext=[]
        for i in contents:
            if i ==" ":
                Etext.append(i)
            else:
                code=ord(i)
                code=code+OF
                if code >126:
                    code=code-94
                char=chr(code)
                Etext.append(char)
        print(Etext)
        encryptedtext=(''.join(Etext))
        print(''.join(Etext))

        filename=input ("What is your file going to be called")

        with open(filename,"w")as f:
              f.write(encryptedtext)

        continue


        def decrypt():
              file = input("""Please enter the name of your text file to be decrypted:
             """)
        if not file.endswith('.txt'):
              file+='.txt'
        try:
              with open (file, 'r') as file:
                    texts= file.read()
        except IOError:
              print("Error- please try again")


  character_key= input ("\nPlease enter the EXACT eight character key that was used to encrypt the message: ")

  offsetfactor_decrypt = sum(map(ord, character_key))//8-32
  result =  ''
  for letter in text:
              if letter == " ":
                    result += " "
  else:
        n = ord(letter) - offsetfactor_decrypt
        if n <33:
              n = n+ 94
              result = result + chr(n)

  print ("\nHere is your decrypted text: \n",result,)

我遇到的问题是每次运行时都会显示:

Traceback (most recent call last):
  File "C:\Users\Callum Bowyer\Desktop\Text Encryption\Project2.py", line 105, in <module>
    for letter in text:
NameError: name 'text' is not defined

2 个答案:

答案 0 :(得分:2)

你的代码编写得非常糟糕且非常糟糕(python中的缩进非常重要,如果你的代码没有正确缩进,你将会遇到语法错误而无法执行该代码,请参阅http://www.python-course.eu/python3_blocks.php) 。所以我尽可能地修复你的代码:

  • 首先运行你的代码我需要修复孔程序中的缩进,
  • 然后我在操作符(+, - ,= ...符号)周围放置空格,你的程序可以在没有这个的情况下工作,但它更容易阅读并试图理解写得很好的代码,
  • 之后我运行了你的代码并试图找出问题所在,这些是我在代码中更改的内容:

    • 您已使用

      if not file.endswith('.txt'):
          file += '.txt'`
      

      检查要解密的文本文件的名称是否具有'.txt'扩展名,因此我添加了相同的代码以检查要加密的文本文件的名称和将保存加密文本的文本文件的名称是否为'。 txt'扩展,

    • 执行if choice == "1":的后续代码块我添加了elif choice == "2":并在decrypt()语句之后放置了elif函数中的所有代码,
    • 我添加了另一个elif语句

      elif choice == "3":
          break
      

      所以当用户输入3程序停止执行时,

    • 您的函数Create8()offset(key)无效,首先在您创建Create8()的函数numlist中创建charlist并从函数创建Create8() return charlist offset(key)您之后调用函数key,其中参数charlist从函数Create8()返回offset(key),函数store你创建numlistCreate8()函数Create8()相同,所以为了使代码生效,我将函数offset(key)Create8_and_offset()合并到一个函数{{ 1}}

      def Create8_and_offset():
      charlist=[]
      total = 0
      for i in range(8):
          num = random.randint(33,126)
          total += num
          char = chr(num)
          charlist.append(char)
      oFactor = (total//8 - 32)
      return charlist, oFactor
      
    • 最后您的代码引发NameError的原因是(Nullmannexus66zaph已在评论中提及)而不是不存在你使用的变量text应该使用变量texts,你应该使用它:

      for letter in texts:
      

      而不是:

      for letter in text:
      

完整(固定)的代码:

import random


def fileopen():
    filename = input("What is the file you need to encrypt: ")
    if not filename.endswith('.txt'):       # this was added to check
        filename += '.txt'                  # that file has .txt extension
    print(filename)
    with open(filename) as wordfile:
        contents = wordfile.read()
    return contents


def Create8_and_offset():
    charlist=[]
    total = 0
    for i in range(8):
        num = random.randint(33,126)
        total += num
        char = chr(num)
        charlist.append(char)
    oFactor = (total//8 - 32)
    return charlist, oFactor


##def Create8():
##    numlist=[]
##    charlist=[]
##    for i in range (8):
##        num=random.randint(33,126)
##        numlist.append(num)
##    for i in numlist:
##        char = chr(i)
##        charlist.append(char)
##    return charlist
##
##def offset(key):
##    store=[]
##    for i in key:
##        num=ord(i)
##        store.append(num)
##    total=sum(store)
##    oFactor=((total//8)-32)
##    return oFactor



while True:
    print("Hello, welcome to the encryption/decryption program")
    print("1 - Encryption")
    print("2 - Decryption")
    print("3 - Exit")
    choice = input("Enter a Number: ")

    if choice == "1":
        print("Encryption Selected")
        contents = fileopen()
        print(contents)
        #Characterkey = Create8()
        #OF = offset(Characterkey)
        Characterkey, OF = Create8_and_offset()
        print("The Characterkey is:\n" + ''.join(Characterkey))
        print("The offset factor is:")
        print(OF)

        Etext=[]
        for i in contents:
            if i == " ":
                Etext.append(i)
            else:
                code = ord(i)
                code = code + OF
                if code > 126:
                    code = code - 94
                char = chr(code)
                Etext.append(char)
        print(Etext)
        encryptedtext = (''.join(Etext))
        print(encryptedtext)

        filename = input("What is your file going to be called: ")
        if not filename.endswith('.txt'):       # this was added to check
            filename += '.txt'                  # that file has .txt extension

        with open(filename,"w")as f:
            f.write(encryptedtext)

        #continue

    elif choice == "2":

    #def decrypt():
        file = input("Please enter the name of your text file to be decrypted:\n")
        if not file.endswith('.txt'):
            file += '.txt'
        try:
            with open (file, 'r') as file:
                texts = file.read()
        except IOError:
            print("Error- please try again")


        character_key = input("\nPlease enter the EXACT eight character key that was used to encrypt the message: ")

        offsetfactor_decrypt = sum(map(ord, character_key))//8-32
        result =  ''
        #for letter in text:
        for letter in texts:
            if letter == " ":
            result += " "
            else:
                n = ord(letter) - offsetfactor_decrypt
                if n < 33:
                    n = n + 94
                result += chr(n)

        print ("\nHere is your decrypted text: \n", result)

    elif choice == "3":
        break

答案 1 :(得分:0)

我的建议是阅读python介绍pdf。 您的代码存在各种错误。 学习python基础知识将对你有所帮助。 尝试了解更多函数和循环。