[英]What does "NameError: name not defined" mean?
So I've been working on my text encryption and decryption program, and I am stuck.所以我一直在研究我的文本加密和解密程序,但我被卡住了。 This is what I have so far:
这是我到目前为止:
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,)
The problem I am having is this is displayed every time I run it:我遇到的问题是每次运行时都会显示:
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
Your code is badly and ineffectively written and really badly indented (indentation in python is very important and if your code is not indented correctly you will get syntax error and not be able to execute that code, see http://www.python-course.eu/python3_blocks.php ).你的代码写得很糟糕,效率很低,缩进也很糟糕(python中的缩进非常重要,如果你的代码没有正确缩进,你会得到语法错误并且无法执行该代码,请参阅http://www.python-course .eu/python3_blocks.php )。 So i tried to fix your code as much as possible:
所以我试图尽可能地修复你的代码:
after that i ran your code and tried to find out where is the problem, these are things that I changed in your code:之后,我运行了您的代码并试图找出问题出在哪里,这些是我在您的代码中更改的内容:
you already used你已经用过
if not file.endswith('.txt'): file += '.txt'`
to check if name of text file to be decrypted has '.txt' extension, so I added same code to also check if name of text file to be encrypted and name of text file where encrypted text would be saved have '.txt' extensions,检查要解密的文本文件的名称是否具有“.txt”扩展名,因此我添加了相同的代码来检查要加密的文本文件的名称和保存加密文本的文本文件的名称是否具有“.txt”扩展名,
if choice == "1":
I added elif choice == "2":
and put all code from decrypt()
function after that elif
statement,if choice == "1":
的 after 代码块if choice == "1":
我添加了elif choice == "2":
并将decrypt()
函数中的所有代码放在该elif
语句之后, I added another elif
statement我添加了另一个
elif
语句
elif choice == "3": break
so when user enters 3
program stops executing,所以当用户输入
3
程序停止执行时,
your functions Create8()
and offset(key)
are ineffective, first in function Create8()
you create numlist
from which than you create charlist
and from function Create8()
you return charlist
, after that you call function offset(key)
where argument key
is charlist
returned from function Create8()
, in function offset(key)
you create store
which is identical to numlist
from function Create8()
, so to make your code effective I merged functions Create8()
and offset(key)
to one function Create8_and_offset()
您的函数
Create8()
和offset(key)
无效,首先在函数Create8()
创建numlist
,然后从中创建charlist
并从函数Create8()
return charlist
,然后调用函数offset(key)
where 参数key
在charlist
从函数返回Create8()
在功能offset(key)
创建store
这是相同的numlist
从功能Create8()
这样使你的代码有效我合并功能Create8()
和offset(key)
,以一种功能Create8_and_offset()
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
and finally the reason why your code raises NameError
is ( Nullman , nexus66 and zaph have mentioned it in comments) that instead of non-existing variable text
that you use you should use variable texts
, you should use this:最后,为什么你的代码引起的原因
NameError
是( Nullman , nexus66和zaph在评论中提到它),与其不存在的变量text
,你使用你应该使用可变texts
,你应该这样做:
for letter in texts:
instead of this:而不是这个:
for letter in text:
Full (fixed) code that works:有效的完整(固定)代码:
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
My suggestion would be to read a python introduction pdf.我的建议是阅读 python 介绍 pdf。 Your code has all kinds of errors over it.
你的代码有各种各样的错误。 Studying python basics will help you a lot.
学习python基础知识会对你有很大帮助。 Try getting to know more of functions and loops.
尝试了解更多的函数和循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.