Python Forum
List index out of range error when attempting to make a basic shift code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List index out of range error when attempting to make a basic shift code
#1
I'm trying to make a basic shift, my code is as follows:

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',]

def shift():
    message = input("Please enter a message:")
    number = int(input('Please enter the number that you would like to shift by (1-26):'))
    new_message = ""
    for letter in message:
        letter = letter.lower()
        if letter.isalpha():
            new_position = alphabet.index(letter) + number
            if new_position > 26:
                new_position = new_position - 27
            new_letter = alphabet[new_position]
        elif letter.isnumeric():
            letter = letter
            print(letter)
        elif letter == " " or letter == "," or letter == "." or letter == ";" or letter == ":":
            letter = letter
            print(letter)
        else:
            print("Error in message please try a different message")
        print(new_message)
        print()


def decode():
    message = input("Please enter a message to decode:")
    number = int(input('Please enter the number shift key (between 1 and 26):'))
    new_message = ""
    for letter in message:
        letter = letter.lower()
        #y = alphabet.index(x)
        #y = y + number
        if letter.isalpha():
            new_position = alphabet.index(letter) - number
            if new_position < 0:
                new_position = new_position + 27
            new_letter = alphabet[new_position]
            new_message = new_message + new_letter
        elif letter.isnumeric():
            letter = letter
            print(letter)
        elif letter == " " or letter == "," or letter == "." or letter == ";" or letter == ":":
            letter = letter
            print(letter)
        else:
            print("Error in message please try a different message")
    print(new_message)
    print()


def main():
    repeat = True
    while repeat == True:
        print("1) Make a code")
        print("2) Decode a message")
        print("3) Quit")
        print()
        choice = int(input("Enter your selection:"))
        if choice == 1:
            shift()
        elif choice == 2:
            decode()
        elif choice == 3:
            repeat = False
        else:
            print("Incorrect choice, please try again")
            choice = int(input("Enter your selection:"))

main()
However I get the following error:

Error:
File "c:/Users/djwil/Documents/python/learning python/Chapter 19 - Chunky Challenges/Shift Code.py", line 70, in <module> main() File "c:/Users/djwil/Documents/python/learning python/Chapter 19 - Chunky Challenges/Shift Code.py", line 63, in main decode() File "c:/Users/djwil/Documents/python/learning python/Chapter 19 - Chunky Challenges/Shift Code.py", line 38, in decode new_letter = alphabet[new_position] IndexError: list index out of range
However I thought that the lines of code:
if new_position < 0:
                new_position = new_position + 27
and:

            if new_position > 26:
                new_position = new_position - 27
should be preventing this from happening. Can anyone help?
Reply
#2
There are only 26 letters in alphabet, not 27. The maximum value for new_position is 25, not 26.
Reply
#3
Rather than keeping track with another number (so you have something to change in multiple places), you can use the mod operator and the actual array.

Instead of
            if new_position > 26:
                new_position = new_position - 27
Consider
            new_position %= len(alphabet)
Reply
#4
if z is in the message, then the program will attempt to shift z to the next available value in the list, this does not exist. Maybe add an if statement (psuedocode):
if z is in the message:
    turn z into a
Reply
#5
(Aug-16-2020, 06:22 PM)bowlofred Wrote: Consider
            new_position %= len(alphabet)
Works for positive and negative values. No need for an if.
x = -2 % 26
y = 28 % 26
print(x, y)
Output:
24 2
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  hi need help to make this code work correctly atulkul1985 5 770 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 675 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Cleaning my code to make it more efficient BSDevo 13 1,354 Sep-27-2023, 10:39 PM
Last Post: BSDevo
  Why do I have to repeat items in list slices in order to make this work? Pythonica 7 1,320 May-22-2023, 10:39 PM
Last Post: ICanIBB
  pyscript index error while calling input from html form pyscript_dude 2 970 May-21-2023, 08:17 AM
Last Post: snippsat
  Index error help MRsquared 1 762 May-15-2023, 03:28 PM
Last Post: buran
Thumbs Down I hate "List index out of range" Melen 20 3,300 May-14-2023, 06:43 AM
Last Post: deanhystad
  how to make bot that sends instagram auto password reset code kraixx 2 1,355 Mar-04-2023, 09:59 PM
Last Post: jefsummers
  Find a shift between 2 pictures TazFleck 0 1,141 Jan-18-2023, 09:56 PM
Last Post: TazFleck
  help me to make my password list in python >>> Oktay34riza 0 574 Dec-23-2022, 12:38 PM
Last Post: Oktay34riza

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020