我正在研究創建凱撒密碼和vigenere密碼的在線課程,但我們首先創建了兩個函數;一個用於查找字母變量中的字母位置,另一個用於將給定字符旋轉給定的時間量(我已經看到ord()和chr()更好地工作,但是該任務要求我們專注於更簡單的概念現在,我猜)。具有所需功能的Python Vigenere密碼
我能夠得到凱撒函數的工作,但我不確定如何繼續使用vigenere密碼。我觀看了許多視頻並瀏覽了這個網站,但還沒有發現任何允許保留空格和非字母字符的內容。任何人都可以指出我如何開始vigenere功能的正確方向?
#Create function alphabet_position(letter) to turn letter into number
#such as a=0 or e=4, using lowercase to make sure case doesnt matter.
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(char, rot)
return list1
def main():
x = input("Type a message: ")
y = input("Rotate by: ")
#result = rotate_character(x, y) #Not needed once encrypt function works.
result = encrypt(x, y)
print (result)
if __name__ == '__main__':
main()
使您的字母表涵蓋任何你想要的字符;添加'%len(字母)'。用'rot'加密;用len(alphabet)-rot'解密。 –
你說什麼我應該把模Len(字母)放在哪裏?在我目前的加密功能? –
in'rotate_character'而不是'%26' ... –