我正在为受控评估的一部分编写凯撒密码。我建立了一个功能齐全的程序,我以为我搞砸了,但是在改变了一些事情之后,我回去检查了一下,一切都出错了!
代码很不整洁,但我现在有点厌倦了编码,并且已经上网了解其他人的观点。
代码:
answer ="C"
while answer == "C":
lettersList=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def menu():
userChoice=input("Would you like to encrypt or decrypt a message? E or D.\n").lower()
while userChoice != "e" and userChoice != "d":
print("Invalid.")
userChoice=input("Would you like to encrypt or decrypt a message? E or D.\n").lower()
print("\n")
return userChoice
def getPlaintext():
plaintext= input("Please enter the message you would like encrypted/decrypted\n").lower()
while plaintext.isalpha() == False:
print("Invalid")
plaintext=input("Please enter the message you would like encrypted/decrypted\n").lower()
print("\n")
return plaintext
def getKey():
key=int(input("Please enter a key. 1-26\n"))
while key > 26 or key < 1:
print("Invalid.")
key=int(input("Please enter a key. 1-26\n"))
print("\n")
return key
def encryptText(plaintext,key):
characterNumber = 0
newMessage = ""
for characters in plaintext:
character = plaintext[characterNumber]
characterPosition = lettersList.index(character)
newPosition=character+key
newLetter = lettersList[newPosition]
newMessage = (newMessage+newLetter)
characterNumber= characterNumber+1
print(newMessage)
def decryptText(plaintext,key):
characterNumber = 0
newMessage = ""
for characters in plaintext:
character = plaintext[characterNumber]
characterPosition = lettersList.index(character)
print(characterPosition)
newPosition=characterPosition-key
newLetter = lettersList[newPosition]
newMessage = (newMessage+newLetter)
characterNumber= characterNumber+1
newMessage = (newMessage.lower())
print(newMessage)
userChoice=menu()
plaintext=getPlaintext()
key=getKey()
if userChoice == "e":
encryptText(plaintext,key)
elif userChoice == "d":
decryptText(plaintext,key)
print(newMessage)