您好,我正在尝试一个简单的密码程序,该程序将按用户输入的值移动字母,但是,当该单词包含字母“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 new_position > len(alphabet):
for i in alphabet.index(i - 1)
#here where I get stuck
print(f"You new encrypted word is {cipher_word}")
encrypt(plain_text=text, shift_amount=shift)
Run Code Online (Sandbox Code Playgroud)
如果总和position and shift amount高于 26,那么它将显示索引超出范围错误,因为总字母表大小为 26。要保持位置索引始终在 26 之间,请将 new_position 乘以 26。
new_position = (position + shift_amount)%26
Run Code Online (Sandbox Code Playgroud)