我已经开始在密码学方面做一些阅读,并为Caesar密码编写一个简单的函数。有没有办法将if, elif, else
语句压缩成一个语句。我觉得有一种方法我现在似乎无法想到它。谢谢!
from string import maketrans
def basic_cypher(message, shift):
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if shift <= 26:
shifted_letters = letters[shift:] + letters[:shift]
elif shift <= -1:
shifted_letters = letters[:shift] + letters[shift:]
else:
shifted_letters = letters[shift - 26:] + letters[:shift - 26]
trans_tab = maketrans(letters, shifted_letters)
return 'This is the encoded version of your message: ', message.translate(trans_tab)