2017-06-14 57 views
1

我正在關注python的在線課程,目前我們正在研究凱撒密碼。我在這個網站上看到了很多關於這個主題的問題,但是沒有必須要使用以前的功能,例如在我的代碼中。前兩個函數工作得很好,當我用多個輸入測試它們時,但是當我添加最後一個函數encrypt時,我得到一個未找到子字符串的值錯誤。我迷失在我最後一部分應該做的事情上。有沒有人有建議,將我推向正確的方向?具有必備功能的凱撒密碼

def alphabet_position(letter): 
    alphabet ="abcdefghijklmnopqrstuvwxyz" #Lists alphabet for a key 
    lower_letter = letter.lower() #Makes any input lowercase. 
    return alphabet.index(lower_letter) #Returns the position of input as a number. 

def rotate_character(char, rot): 
    alphabet = "abcdefghijklmnopqrstuvwxyz" 
    if char.isalpha(): 
     a = alphabet_position(char) 
     a = (a + rot) % 26   #needs modulo 
     a = (alphabet[a]) 
     if char.isupper(): 
      a = a.title() 
     return a 
    else: 
     return char 

def encrypt(text, rot): 
    list1 = "" 
    for char in text: 
     list1 += rotate_character(text, rot) 
    return list1 

def main(): 
    x = input("Type a message: ") 
    y = int(input("Rotate by: ")) 
    #result = rotate_character(x, y) #Not needed once encrypt function works. 
    result = encrypt(x, y) 
    print (result) 

if __name__ == '__main__': 
    main() 
+0

你應該使用'ord'和'chr'得到的字母,而不是在一個字符串搜索的ASCII碼。另外:使用'codecs.encode(「foo」,「rot13」)'在1行中也是一樣的...... –

+0

@ Jean-FrançoisFabre我毫不懷疑你是對的,但這是一個初學者課程,希望我使用課堂上沒有教授的功能或方法。我會研究這些以供將來參考,謝謝! –

回答

0

您想單獨旋轉每個單獨的字符,但要將完整的文本傳遞給旋轉函數。

而是使用:

def encrypt(text, rot): 
    list1 = "" 
    for char in text: 
     list1 += rotate_character(char, rot) # "char", not "text" 
    return list1 
+0

謝謝,完美的工作!這些小的參數混淆現在似乎是我的主要問題lol –

+0

不客氣。如果有幫助,請隨時將答案標記爲已接受和/或提出答案。 –