Python 名字没有定义,搞不清楚我哪里做错了?
目前正在做一些学校编程,我很困惑我在这里哪里出错了:Python 名字没有定义,搞不清楚我哪里做错了?,python,python-3.x,Python,Python 3.x,目前正在做一些学校编程,我很困惑我在这里哪里出错了: #declaring array names. longitude=[]; latitude=[]; messagetext=[];encryptions=[]; input_file = open('messages.txt', 'r') lines_in_file_array = input_file.read().splitlines() input_file.close() #appending the lines in a s
#declaring array names.
longitude=[]; latitude=[]; messagetext=[];encryptions=[];
input_file = open('messages.txt', 'r')
lines_in_file_array = input_file.read().splitlines()
input_file.close()
#appending the lines in a select file to select records.
for line in lines_in_file_array:
record_array = line.split(',')
longitude.append(record_array[0])
latitude.append(record_array[1])
messagetext.append(record_array[2])
def encrypt():
for index in range(len(messagetext)):
x=messagetext[index]
x=([ord(character)+2 for character in x])
#the character under this seems to not like being defined. I'm confused?
codedx=str.join(chr(character),'','','','')
encoded_text.append(codedx)
print(codedx)
encrypt()
print(messagetext)
我一直得到一个错误,“字符”没有定义。我已经发表了内部评论,以帮助您确定原因
x=([ord(character)+2 for character in x])
字符
是列表理解的局部变量。这在外面是没有定义的
在一些简单的例子中很容易看到:
[i for i in range(10)]
print(i) # NameError: name 'i' is not defined
您遇到的问题与范围有关。character变量仅存在于列表中装箱的伪for循环中。要解决这个问题,您需要1)访问X中的字符,或者2)创建一个for循环来保存charachter的存在 例如:
#declaring array names.
longitude=[]; latitude=[]; messagetext=[];encryptions=[];
input_file = open('messages.txt', 'r')
lines_in_file_array = input_file.read().splitlines()
input_file.close()
#appending the lines in a select file to select records.
for line in lines_in_file_array:
record_array = line.split(',')
longitude.append(record_array[0])
latitude.append(record_array[1])
messagetext.append(record_array[2])
def encrypt():
for index in range(len(messagetext)):
x=messagetext[index]
for y in x:
charachter = ord(y)+2
#the character under this seems to not like being defined. I'm confused?
codedx=str.join(chr(character),'','','','')
encoded_text.append(codedx)
print(codedx)
encrypt()
print(messagetext)
正如错误告诉您的那样,
字符
未定义。这是正确的。如果查看encrypt
方法内部,您试图使用字符
,但从未声明它或为它赋值。您的代码中应该有什么character
?除了@idjaw的注释外,在python中,我们通常将数组称为列表。@idjaw是指循环中每个字符的ASCII码。我试图将每个字符依次转换为ASCII码,添加两个字符,然后返回。我现在有点不明白该怎么做。你在列表中创建x
,然后不使用它。您需要在另一个理解中应用chr
。