2016-10-03 80 views
0

你好,並提前致謝。在python 3中使用ASCII加密

我正在努力使一個密碼學程序,我必須爲學校做。我不是高級Python專家,所以如果這是一個愚蠢的問題,我很抱歉。當我運行這個程序並插入例如abc與班次2它將返回cde這是很好的。但我試圖插入xyz以及移位3,而不是正確移位abc它返回aaa。這也會發生,如果我使用shift 2然後它返回zaa。我怎麼能當字母與ASCII TABEL

shift = int(input("Please insert a number you want to shift the characters with: ")) 

end = "" 

for x in alf: 
    ascii = ord(x) 

if ascii >= 97 and ascii <= 122: 
    res = ascii + shift 
    if res > 122: 
     res = 0 + 97 
     min = res + shift 
    end = end + chr(min) 

print (end)         
+3

如果'res'大於122則將其設置爲97的固定值。 – Matthias

回答

0

這是因爲你的邏輯表達式是錯誤的做調整我的程序正確地從頭開始。這裏是一個例子,它將允許任何正整數作爲右移,從再次開始。它可以非常優化(提示:使用模運算符),但是這是對你的代碼和數字大寫的大的改動。

for x in alf: 
    ascii = ord(x) 

    if ascii >= 97 and ascii <= 122: 
    res = ascii + shift 
    while res > 122: 
     res = res - (122 - 97) - 1 
    end = end + chr(res) 
+0

非常感謝stefan! –