[英]Finding consecutive last letters: list index out of range when trying to loop through consecutive letters
[英]How to loop through a list again when index out of range
嗨,我正在嘗試一個簡單的密碼程序,它將按用戶輸入的值移動字母,但是,當單詞有字母“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)
如果position and shift amount
的總和高於 26,那么它將顯示索引超出范圍錯誤,因為總字母大小為 26。要保持 position 索引始終在 26 之間,然后將 new_position 修改為 26。
new_position = (position + shift_amount)%26
我認為這段代碼將解決您的問題...
def encrypt(plain_text, shift_amount):
cipher_word = ""
for letter in plain_text:
position = ord(letter)-97
new_letter=(chr(97+(position+shift_amount) % 26))
cipher_word += new_letter
print(f"You new encrypted word is {cipher_word}")
encrypt(plain_text=text, shift_amount=shift)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.