-2
當我最後一個問題中的一個沒有得到很好的回答後,我決定考慮這個問題的所有答案(對吧?)。一個困擾我的是定義/調用一個簡單的函數。如何定義這些功能?
我明白主要想法,並且可以在小(簡單)的範圍內完成。例如:
def multiply(x, y):
return x*y
numb1 = 2
numb2 = 3
print(multiply(numb1, numb2))
很簡單。現在我想要做的是通過定義函數來清理我的Vigenere密碼,並且困擾我的是什麼參數以及爲什麼。我不想改變(可能寫得不好,不開心)代碼,但我只想看看在使用定義的函數後它會如何看待它。
message = input("Enter a message to encrypt:\n").upper().replace(" ", "")
print("Enter your encryption key ("+str(len(message)),"or less letters.): ")
key = input().upper().replace(" ", "")
div_times = int(int(len(message))/int(len(key)))
remainder = int(len(message))%int(len(key))
key_ring = (((key)*(div_times+1))[:-(len(key)-remainder)])
alph = 26
print("-------\n"
"Message: ",message,"\n"
"Key: ",key_ring,
"\n-------")
mvalues = [0]*len(message)
kvalues = [0]*len(key_ring)
m_position = 0
k_position = 0
for letter in message:
mvalues[m_position] = ord(letter)
m_position += 1
for key in key_ring:
num = alph - (int(ord("Z")) - int(ord(key)))
kvalues[k_position] = num - 1
k_position += 1
m_position = 0
k_position = 0
print("\nEncrypted message: ", end="")
for character in message:
newletter_v = (mvalues[m_position] + kvalues[k_position])
if newletter_v > ord("Z"):
newletter_v -= 26
elif newletter_v < ord("A"):
newletter_v += 26
print(chr(newletter_v)+"", end="")
m_position += 1
k_position += 1
我試過的東西結合,我不斷收到錯誤或不正確的輸出:
def encryptMessage(message, key):
mvalues = [0]*len(message)
kvalues = [0]*len(key_ring)
m_position = 0
k_position = 0
for letter in message:
mvalues[m_position] = ord(letter)
m_position += 1
for key in key_ring:
num = alph - (int(ord("Z")) - int(ord(key)))
kvalues[k_position] = num - 1
k_position += 1
message = input("Enter a message to encrypt:\n").upper().replace(" ", "")
print("Enter your encryption key ("+str(len(message)),"or less letters.): ")
key = input().upper().replace(" ", "")
div_times = int(int(len(message))/int(len(key)))
remainder = int(len(message))%int(len(key))
key_ring = (((key)*(div_times+1))[:-(len(key)-remainder)])
alph = 26
print("-------\n"
"Message: ",message,"\n"
"Key: ",key_ring,
"\n-------")
mvalues = [0]*len(message)
kvalues = [0]*len(key_ring)
m_position = 0
k_position = 0
encryptMessage(message, key)
m_position = 0
k_position = 0
print("\nEncrypted message: ", end="")
for character in message:
newletter_v = (mvalues[m_position] + kvalues[k_position])
if newletter_v > ord("Z"):
newletter_v -= 26
elif newletter_v < ord("A"):
newletter_v += 26
print(chr(newletter_v)+"", end="")
m_position += 1
k_position += 1