-2

I am trying to make a program that shifts the characters of a message to the right of its position in the alphabet. For example: the input is "abc" and the output would be "bcd".

Currently this is the code:

import string

alphabet = list(string.ascii_lowercase)
codelist = []

code = input("input text message: ")
for char in code:
    codelist.append(char)
for x in codelist:
    for y in alphabet:
        if y == x and x != " ":
            x = alphabet[alphabet.index(y) + 1]

Traceback:

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\pythonProject1\file.py", line 12, in <module>
    x = alphabet[alphabet.index(y) + 1]
IndexError: list index out of range
Ben
  • 1
  • for last element in your `alphabet` list i.e `z` your code is breaking because you are trying to fetch at alphabet[location_of`z`+ 1] which will be more than index in your list. – Deepak Tripathi Oct 23 '22 at 04:34
  • You are using `x` as a loop variable in the outer loop `for x in codelist`, but you are also using `x` in the inner loop `x = alphabet[alphabet.index(y) + 1]` what are you expecting to happen here? Try putting `print(alphabet.index(y), x, y)` right about that line and see if it's doing what you hope. – Mark Oct 23 '22 at 04:37
  • This line also not correct `x = alphabet[alphabet.index(y) + 1]` because you are assigning the x two times one in the initial loop and inside loop as well – Deepak Tripathi Oct 23 '22 at 04:37
  • initialize `z = ""` before your loop and replace `x = alphabet[alphabet.index(y) + 1]` to `z += alphabet[alphabet.index(y) + 1]` your code will work fine for all the cases except last 3 characters of alphabets. – Deepak Tripathi Oct 23 '22 at 04:39
  • Welcome to Stack Overflow. It's not clear to me what the question is. If it's "why does this error occur?", then think carefully about what will happen the last time through the loop - what will be the value of the index? If it's "what's wrong with the code?", then I don't think your approach to solving the problem really makes sense at all - please start by trying to write out the intended steps, in English, in a separate document. If it's "how can I write correct code for this task?" then [please start with research](https://meta.stackoverflow.com/questions/261592/). – Karl Knechtel Oct 23 '22 at 04:42
  • https://stackoverflow.com/a/555724/6242321 for ```string.translate``` which does this. – jwal Oct 23 '22 at 04:46

3 Answers3

1

This is a Caesar shift. Here is a Caesar shift implementation handling spaces, digits, and alphabetical characters. Just give it a string and the "shift" that you want the characters to change by.

# a function that takes prompts the user for a string and a shift value
# and returns the encoded string
def shift():
    # prompt the user for a string
    string = input("Enter a string: ")
    # prompt the user for a shift value
    shift = int(input("Enter a shift value: "))
    # create an empty string
    new_string = ""

    # shift string based on shift value
    for i in string:
        # if the character is a space, add it to the new string
        if i == " ":
            new_string += i
        # if the character is a lowercase letter, shift it
        elif i.islower():
            # if the character is shifted past z, wrap around to a
            if ord(i) + shift > ord("z"):
                new_string += chr(ord(i) + shift - 26)
            # otherwise, shift the character
            else:
                new_string += chr(ord(i) + shift)
        # if the character is an uppercase letter, shift it
        elif i.isupper():
            # if the character is shifted past Z, wrap around to A
            if ord(i) + shift > ord("Z"):
                new_string += chr(ord(i) + shift - 26)
            # otherwise, shift the character
            else:
                new_string += chr(ord(i) + shift)
        # if the character is a number, shift it
        elif i.isdigit():
            # if the character is shifted past 9, wrap around to 0
            if ord(i) + shift > ord("9"):
                new_string += chr(ord(i) + shift - 10)
            # otherwise, shift the character
            else:
                new_string += chr(ord(i) + shift)
        # if the character is a special character, shift it
        else:
            new_string += chr(ord(i) + shift)

    # return the new string
    print("DEBUG: " + new_string)

# call the function
shift()
Khoi Nguyen
  • 351
  • 1
  • 10
0

Actually, your code will break if someone enters 'z' in their input your code will break. Also, if someone enters an uppercase letter then your code will just skip that uppercase letter. You can solve these small errors by changing the input to lowercase form like this:

code = input('input text message: ')
code = code.lower()

For the second error you can add an if statement. So, whenever it faces 'z' in the input it will just specify the value of char to 'a' You can achieve this like this

if y == x and x != " " and x !="z":
    char = alphabet[alphabet.index(y) + 1]
    moved += char
elif y == x and x == "z":
    char = 'a'
    moved +=char

If you are wondering about that moved variable then this is just a variable storing the shifted letters for example if the input is 'The' then for every iteration the shifted chracter will be added to the moved variable. And the value of moved variable will update like this

1. u
2. ui
3. uif

After the program ends you should also print this value to the console using the print statement.

print(moved)

Your code will now look like this:

import string

alphabet = list(string.ascii_lowercase)
codelist = []

moved = ""

code = input("input text message: ")
code = code.lower()
for char in code:
    codelist.append(char)
for x in codelist:
    for y in alphabet:
        if y == x and x != " " and x !="z":
            char = alphabet[alphabet.index(y) + 1]
            moved += char
        elif y == x and x == "z":
            char = 'a'
            moved +=char

print(moved)
        
Pythonista
  • 185
  • 12
-1

You could do this simply with ord and slicing

alphabet = string.ascii_lowercase
codelist = []

code = input("input text message: ")
code = code.lower()  # make sure user inputs values between a-z
alphabet[ord(code[0])-ord('a')+1 : ord(code[0])-ord('a')+len(code)+1]
# for abc -> bcd and xyz -> yz
Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21