[英]What does "NameError: name not defined" mean?
所以我一直在研究我的文本加密和解密程序,但我被卡住了。 這是我到目前為止:
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
你的代碼寫得很糟糕,效率很低,縮進也很糟糕(python中的縮進非常重要,如果你的代碼沒有正確縮進,你會得到語法錯誤並且無法執行該代碼,請參閱http://www.python-course .eu/python3_blocks.php )。 所以我試圖盡可能地修復你的代碼:
之后,我運行了您的代碼並試圖找出問題出在哪里,這些是我在您的代碼中更改的內容:
你已經用過
if not file.endswith('.txt'): file += '.txt'`
檢查要解密的文本文件的名稱是否具有“.txt”擴展名,因此我添加了相同的代碼來檢查要加密的文本文件的名稱和保存加密文本的文本文件的名稱是否具有“.txt”擴展名,
if choice == "1":
的 after 代碼塊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)
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
最后,為什么你的代碼引起的原因NameError
是( Nullman , nexus66和zaph在評論中提到它),與其不存在的變量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
我的建議是閱讀 python 介紹 pdf。 你的代碼有各種各樣的錯誤。 學習python基礎知識會對你有很大幫助。 嘗試了解更多的函數和循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.