未定义PYTHON名称“x”

2024-05-16 13:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我不断收到一个错误: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)

完整的错误消息:

^{pr2}$

名称错误:未定义名称“text” 我试图让程序读取用户的输入,并将其转换为备用集。然而,这是行不通的。 我无法确定这个“命名”问题的来源,因为我以前尝试过定义文本,但它不起作用。在

我也没有发现除了hacks之外对定义顺序的充分解释。在

谢谢!在


Tags: textname名称定义ismydef错误
1条回答
网友
1楼 · 发布于 2024-05-16 13:17:59

你想这么做吗?在

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)变量toEncrypt是参数或输入

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

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

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

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

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

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

相关问题 更多 >