2

好的,所以我正在编写一个python加密代码。代码比它需要的要长,所以我把它的一部分切换到函数。我一开始这样做,它就说找不到变量。为了解决这个问题,我将变量设置为全局。但是,它仍然不起作用,并给我错误:

Traceback (most recent call last):
  File "C:/Users/Alex/Desktop/Encryptor.py", line 272, in <module>
    startup()
  File "C:/Users/Alex/Desktop/Encryptor.py", line 257, in startup
    encrypt()
  File "C:/Users/Alex/Desktop/Encryptor.py", line 44, in encrypt
    maincrypt(2)
  File "C:/Users/Alex/Desktop/Encryptor.py", line 12, in maincrypt
    print newtext
UnboundLocalError: local variable 'newtext' referenced before assignment

这是我的代码:

letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def maincrypt(num):
    print otext
    print textlist
    print newtextlist
    print newtext
    print times
    print i
    add = times + num
    while add > 25:
        add = add - 25
        if ord(i) >= 65 and ord(i) <= 90:
            newtext += letters[add].uppercase
        else:
            newtext += letters[add]
def encrypt():
    global otext
    global textlist
    global newtextlist
    global newtext
    global times
    global i
    otext = raw_input("Text?")
    textlist = []
    newtextlist = []
    newtext= ""
    times = 0
    for i in otext:
        textlist.append(i)
    for i in textlist:
        if i == 'a' or i == 'A':
            maincrypt(0)
        elif i == 'b' or i == 'B':
            maincrypt(1)
        elif i == 'c' or i == 'C':
            maincrypt(2)
        elif i == 'd' or i == 'D':
            maincrypt(3)
        elif i == 'e' or i == 'E':
            maincrypt(4)
        elif i == 'f' or i == 'F':
            maincrypt(5)
        elif i == 'g' or i == 'G':
            maincrypt(6)
        elif i == 'h' or i == 'H':
            maincrypt(7)
        elif i == 'i' or i == 'I':
            maincrypt(8)
        elif i == 'j' or i == 'J':
            maincrypt(9)
        elif i == 'k' or i == 'K':
            maincrypt(10)
        elif i == 'l' or i == 'L':
            maincrypt(11)
        elif i == 'm' or i == 'M':
            maincrypt(12)
        elif i == 'n' or i == 'N':
            maincrypt(13)
        elif i == 'o' or i == 'O':
            maincrypt(14)
        elif i == 'p' or i == 'P':
            maincrypt(15)
        elif i == 'q' or i == 'Q':
            maincrypt(16)
        elif i == 'r' or i == 'R':
            maincrypt(17)
        elif i == 's' or i == 'S':
            maincrypt(18)
        elif i == 't' or i == 'T':
            maincrypt(19)
        elif i == 'u' or i == 'U':
            maincrypt(20)
        elif i == 'v' or i == 'V':
            maincrypt(21)
        elif i == 'w' or i == 'W':
            maincrypt(22)
        elif i == 'x' or i == 'X':
            maincrypt(23)
        elif i == 'y' or i == 'Y':
            maincrypt(24)
        elif i == 'z' or i == 'Z':
            maincrypt(25)
        else:
            newtext += i
        times += 1
    print newtext

def decrypt():
    otext = raw_input("Text?")
    textlist = []
    newtextlist = []
    newtext= ""
    times = 0
    for i in otext:
        textlist.append(i)
    for i in textlist:
        if i == 'a' or i == 'A':
            add = 0 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'b' or i == 'B':
            add = 1 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'c' or i == 'C':
            add = 2 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'd' or i == 'D':
            add = 3 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'e' or i == 'E':
            add = 4 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'f' or i == 'F':
            add = 5 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'g' or i == 'G':
            add = 6 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'h' or i == 'H':
            add = 7 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'i' or i == 'I':
            add = 8 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'j' or i == 'J':
            add = 9 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'k' or i == 'K':
            add = 10 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'l' or i == 'L':
            add = 11 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'm' or i == 'M':
            add = 12 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'n' or i == 'N':
            add = 13 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'o' or i == 'O':
            add = 14 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'p' or i == 'P':
            add = 15 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'q' or i == 'Q':
            add = 16 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'r' or i == 'R':
            add = 17 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 's' or i == 'S':
            add = 18 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 't' or i == 'T':
            add = 19 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'u' or i == 'U':
            add = 20 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'v' or i == 'V':
            add = 21 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'w' or i == 'W':
            add = 22 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'x' or i == 'X':
            add = 23 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'y' or i == 'Y':
            add = 24 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        elif i == 'z' or i == 'Z':
            add = 25 - times
            while add < 0:
                add = add + 25
            newtext += letters[add]
        else:
            newtext += i
        times += 1
    print newtext

def startup():
    upass = raw_input("Password: ")
    if upass == "astrocrypt":
        print """Welcome!
1: Encrypt
2: Decrypt
3: Credits
4: Quit"""
        try:
            choice = input()
        except SyntaxError:
            print "Oops! That's not a valid number! Try again!"
            startup()
        except NameError:
            print "Oops! That's not a valid number! Try again!"
            startup()
        if choice == 1:
            encrypt()
            startup()
        elif choice == 2:
            decrypt()
            startup()
        elif choice == 3:
            print "Made by Alex Taber"
            startup()
        elif choice == 4:
            pass
        else:
            print "Unknown number"
            startup()
    else:
        print "Incorrect password!"
startup()
4

2 回答 2

3

首先,有一些非常强大且几乎牢不可破的加密算法,其中一些是用 python 预先打包的,例如 hmac

import hmac

def Hash_string(ref):
        cypher = hmac.new('you secret word', 'plain-text')
        return cypher.hexdigest()

简单易用,功能更强大。您也可以将河豚用于更高级和更安全的项目,尽管默认情况下它不附带 python,但设置起来很简单。

现在到你的代码,这里是如何在 python 中使用全局变量

# declare variables as global
global num1
global num2
num2=22    # give initial value to num2

def foo():
   # bind variable names to the ones in global scope
   global num2
   print num2   # output: 22
   num2 = 88
   print num2   # output: 88
   global num1
   num1 = num2

def bar():
   print num1   # output: 88
   print num2   # output 88

foo()
bar()

所以你需要将 newtext 绑定到声明为 gobal 的那个

我还建议你重写 encrypt 看起来像这样

alpha = ['a','b','c','d','e','f','g','h','i','j','k','l' ,'m','n','o','p','q','r','s','t','u','v','w','x',' y','z']

数字 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 ,24,25]

def map (ch):
   chr = ch.lower()
   return numeric[alpha.index(chr)]

这会创建数字和字母之间的映射,因此您不需要一长串 elif

希望这可以帮助。

编辑您可以使用 global 关键字访问全局变量,但如果要修改它们,首先需要绑定到全局变量,然后才能更改它们。

编辑将 return numeric[index(chr)] 更改为 return numeric[alpha.index(chr)] 对不起这个错误:)

于 2013-05-11T14:12:26.580 回答
2

为了保护程序员免受全局变量的影响,除非您声明全局变量与global variablename. 在 maincrypt 中,您不声明global newtext也不newtext通过分配给它来创建本地。+= 运算符要求左手已经存在 - 它还不存在,因此会引发异常。

顺便说一句,如果您打算在其他任何地方重用此程序,最好使用类变量而不是全局变量,因此 1)如果其他人使用相同的全局名称,一切都可以 2)您可以有两个加密器实例/decryptor 代码运行和加密/解密不同的东西,即使在不同的线程上并行运行,也不会破坏彼此的全局变量。

此外,这段代码:ord(i.upper()) - ord('A')将为'a'和'A'提供0,为'b'和'B'提供1,为'c'和'C'提供2......等等,所以你不需要如此巨大的 if/elif 链。(为什么这样有效是因为 'A'、'B'、'C' 等在 ASCII 中是连续的,所以 'B' - 'A' 是 1 等等)

于 2013-05-11T14:03:33.253 回答