Last answered:

28 Jun 2022

Posted on:

27 Jun 2022

0

Resolved: Error "out of index" even with modulus

My code is below:

def encrypt(text,shift):
    alphabet='abcdefghijklmnopqrstuwxyz'
    output=''
    text=text.lower()
    for char in text:
        if char not in alphabet:
            output=output+char
        else:
            pos=alphabet.find(char)
            output=output+alphabet[(pos+shift)%26]
    return output

If shift is 5 and there is a "u" inside the text, it gives me the error "string index out of range" in line "output=output+alphabet[(pos+shift)%26]". Why can't I write "(pos+shift)%26" instead of calling a function that does the same? Thank you

2 answers ( 1 marked as helpful)
Instructor
Posted on:

28 Jun 2022

1

Hey Alessandro,

Thank you for your question!

Your code is, in fact, absolutely correct. The error comes from the fact that the letter 'v' is missing in the definition of your alphabet string :)

Kind regards,
365 Hristina

Posted on:

28 Jun 2022

0

Ops... thank you for the answer!

Submit an answer