Home > Enterprise >  How can i convert the index of a string that is marked as a string in an integer number?
How can i convert the index of a string that is marked as a string in an integer number?

Time:11-14

I am trying to code a Caesar cipher and i am trying to make a loop around the alphabet so that even if a put a high number as a shifter it doesn't give me an error. The problem is it tells me i can't compare a string with a number, so when i put the new index like this "int(new_index)" i still get an error. The teacher of the course i am following said to just copy and paste the alphabet list twice but what if i put 1000 as a shifter?

def encrypt(message, shifter):
    encrypted_message = ""
    for letter in message:
        if letter == " " :
            encrypted_message  = " "
        else:
            index = alphabet.index(letter)
            new_index = (alphabet[index   shifter])
            while new_index > 25:
                new_index -= 25
    print(f"The encrypted message is {encrypted_message}.")


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



text = (input("Typer your message: \n")).lower()
shift = int(input("Type your shift number: \n"))

encrypt(text, shift) 

My idea was to keep subtracting 25 from the new_index with a while loop when the index is higher then 25, so that even if i put 10000 as the shifter i don't have to copy the list hundreds of time. What am i doing wrong? Thank you all in advance!

CodePudding user response:

set new_index = index shifter then after the while statement put encrypted_message = alphabet[new_index]

the full else statement:

index = alphabet.index(letter)
new_index = index   shifter
while new_index > 25:
    new_index -= 25
encrypted_message  = alphabet[new_index]
  • Related