我正在通过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()发布于 2017-09-07 23:10:57
由于您正在处理.lower()-case letters,因此很容易知道它们的ASCII码范围是97-122。
做移位循环的一个好方法是用0-25的范围来表示每个字母,这是由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()https://stackoverflow.com/questions/46099533
复制相似问题