2014-01-10 141 views
1

我想創建一個簡單的程序來加密一個字符串並返回其加密的字符。For循環問題與加密腳本

但是我有for循環,這是造成Python來顯示錯誤的問題:

Traceback (most recent call last): 
File "C:/Users/Alex/Desktop/Uni/Programming/encrypt", line 18, in <module> 
encrypt(encin) 
File "C:/Users/Alex/Desktop/Uni/Programming/encrypt", line 12, in encrypt 
encout += e6 
UnboundLocalError: local variable 'encout' referenced before assignment 

下面是代碼:

key = 10 
encout = '' 
def encrypt(s): 
    for c in s: 
     if c != ' ' : 
      e1 = ord(s) 
      e2 = e1 - 97 
      e3 = e2 + key 
      e4 = e3 % 26 
      e5 = e4 + 97 
      e6 = chr(e5) 
      encout = encout + e6 
     else: 
      encout = encout + c 
a = input("To encrypt a string type 1, to decrypt a string type 2: ") 
if a == '1': 
    encin = input("Please type the string to encrypt: ")  
encrypt(encin) 
print(encout) 

你可以看到它的任何問題?

謝謝。

回答

3

由於錯誤消息說,你是讀取encout的值,encrypt函數的局部變量,之前聲明它(也就是說,在分配給它之前)。

擺脫encout全局變量 - 這是無用的,並將encout = ''行移動到encrypt的開頭。然後,在encrypt的末尾添加return encout(在for循環終止之後)。更改您的程序的結尾,以便它讀取:

print(encrypt(encin)) 
+0

感謝您的回答,我將使用這個,因爲我不喜歡使用'全局安全'。 – user2975192

2

我認爲你正在試圖做的是:

e1 = ord(c) 

您通過字符串的字符尚未迭代應用ord整個字符串(s),而不是個性c。這是例外原因。

UPDATE:關於encout問題,您需要聲明變量的方法的頂部之前,爲了訪問它,就像這樣:

def encrypt(s): 
    encout = '' 
    # remaining of the method 
+0

謝謝,這是我的愚蠢。我現在顯示錯誤'UnboundLocalError:本地變量'encout'在賦值之前被引用' – user2975192

+0

您正在定義方法外部的'encout'變量並在裏面重新定義它。這意味着可變範圍的問題。最好使'encrypt''返回encout'並將其分配給您的全局'encout'變量。另外,你可以用新信息更新問題嗎? –