您好,我正在尝试一个简单的密码程序,该程序将按用户输入的值移动字母,但是,当该单词包含字母“z”时,它将抛出索引超出范围的错误。因此,为了解决这个问题,我尝试了复制列表的简单方法,但我想使用更好的方法来做到这一点。我想检查索引是否超出范围,然后再次循环列表并执行与代码中所示相同的任务非常感谢!
alphabet = ['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']
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))
def encrypt(plain_text, shift_amount):
cipher_word = ""
indexed_letter = len(alphabet)
for letter in plain_text:
position = alphabet.index(letter)
new_position = position + shift_amount
new_letter = alphabet[new_position]
cipher_word += new_letter
if …Run Code Online (Sandbox Code Playgroud) python ×1