【问题标题】:PYTHON Name 'x" is not definedPYTHON 名称“x”未定义
【发布时间】:2014-09-17 05:52:51
【问题描述】:

我不断收到错误消息:NameError: name 'text' is not defined

def Encryption(i, j):
    diction = {'a':'x1', 'b':'3', 'c':'lk', 'd':'$%', 'e':'^%', 'f':'(*', 'g':'-+', 'h':'il', 'i':'z@', 'j':'@#', 'k':'}{', 'l':'-*', 'm':'p', 'n':':l', 'o':'!#', 'p':'1%', 'q':'k<', 'r':'/', 's':'>', 't':'@', 'u':'if', 'v':'q#$', 'w':'^#1', 'x':'5-=', 'y':'n?', 'z':'v'}
    my_text = input("What would you like to encrypt?")
    text = my_text.lower()
    for diction in text:
        text = text.replace(i, j)
    Encryption(text,diction)

完整的错误消息:

File "Spy1.py", line 39, in <module>
  OpSet()
File "Spy1.py", line 3, in OpSet
  MainMenu()
File "Spy1.py", line 16, in MainMenu
  Encryption(text, diction)

NameError:名称“文本”未定义 我试图让程序读取用户的输入,并将其转换为备用集。但是,它不会起作用。 我无法确定这个“命名”问题的根源,因为我之前尝试定义 Text 但它不起作用。

我也没有找到关于 hacks 之外的定义顺序的充分解释。

谢谢!

【问题讨论】:

  • 最后一行的身份问题。
  • 不要覆盖循环中的变量文本。使用不同的局部变量
  • 伙计们,这是他的第一个问题,别再投反对票了,也许他才 13 岁,而你正在像一个坏蛋老师一样评判。
  • 使用raw_input 而不是input
  • 查看错误消息,您似乎从MainMenu 调用Encryption。您没有显示那段代码,但很可能,text 没有在 MainMenu 中定义。

标签: python nameerror


【解决方案1】:

你想这样做吗?

def encrypt(toEncrypt):
    d = {'a':'x1', 'b':'3', 'c':'lk', 'd':'$%', 'e':'^%', 'f':'(*', 'g':'-+', 'h':'il', 'i':'z@', 'j':'@#', 'k':'}{', 'l':'-*', 'm':'p', 'n':':l', 'o':'!#', 'p':'1%', 'q':'k<', 'r':'/', 's':'>', 't':'@', 'u':'if', 'v':'q#$', 'w':'^#1', 'x':'5-=', 'y':'n?', 'z':'v'}
    temp = toEncrypt.lower()
    toReturn = ""
    for l in temp:
            toReturn += d[l]
    return toReturn

encrypt('test') # returns '@^%>@'

def encrypt(toEncrypt) var toEncrypt 是参数或输入

d = { ... } 是字典d['a'] 将返回x1d['b'] 将返回3

temp = toEncrypt.lower()temp 设置为toEncrypt 的小写版本

toReturn = "" 在 for 循环之外定义了一个新的空白字符串

for l in temp: 循环遍历temp 中的每个字符

toReturn += d[l]l用作字典d的键,并返回对应的值

return toReturn 是函数返回...或输出

【讨论】:

  • 这似乎没有做任何事情,虽然我不完全理解“toReturn+= diction[letter]”的功能。这是在前一个字符串中添加字母吗?编辑:实际上,这正是我想要它做的。你能解释一下添加是如何工作的吗?谢谢!
  • 我更改了代码以使其更易于理解。 toReturn += d[l]toReturn = toReturn + d[l] 是一样的,它是一种连接形式。
  • 谢谢!您添加的解释澄清了界限。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
相关资源
最近更新 更多