我正在通过John Zelle撰写的计算机科学入门书来学习编码。我坚持锻炼5.8。我需要以某种方式修改这个解决方案,其中下一个字符是" z"是" a"为了使它循环。任何帮助都会很棒:)
def main():
print("This program can encode and decode Caesar Ciphers") #e.g. if key value is 2 --> word shifted 2 up e.g. a would be c
#input from user
inputText = input("Please enter a string of plaintext:").lower()
inputValue = eval(input("Please enter the value of the key:"))
inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
#initate empty list
codedMessage = ""
#for character in the string
if inputEorD == "e":
for ch in inputText:
codedMessage += chr(ord(ch) + inputValue) #encode hence plus
elif inputEorD =="d":
codedMessage += chr(ord(ch) - inputValue) #decode hence minus
else:
print("You did not enter E/D! Try again!!")
print("The text inputed:", inputText, ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)
main()
答案 0 :(得分:0)
由于您正在处理.lower()
- 大小写字母,因此可以确定其ASCII范围是[97-122]。
制作移动圆形的一个好方法是用[{0}]代表每个字母,由ord(ch) - 97
完成,然后添加密钥,然后用26对结果进行模数设置,这样就可以了变为(ord(ch) - 97 + key)%26
,然后我们在范围[0-25]中得到一个结果,然后添加97将得到它的ASCII码:
def main():
print("This program can encode and decode Caesar Ciphers")
inputText = input("Please enter a string of plaintext:").lower()
inputValue = int(input("Please enter the value of the key:")) # use int(), don't eval unless you read more about it
inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
codedMessage = ""
if inputEorD == "e":
for ch in inputText:
codedMessage += chr((ord(ch) - 97 + inputValue)%26 + 97)
elif inputEorD =="d":
codedMessage += chr((ord(ch) - 97 - inputValue)%26 + 97)
else:
print("You did not enter E/D! Try again!!")
print("The text inputed:", inputText, ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)
main()