Index error: String out of range, but it shouldn't be going out of range?

Alright so I am making an encoder/decoder and currently I'm testing to see if my idea will work, but I keep getting the error telling me my string index is out of range when it shouldn't be going out of range in the first place.

message = "abc"
#Should come out as 212223
translated = ' '


n = 1
while n >= 0:
    t = message[n]
    if t == 'a':
        translated = translated + '21'
    elif t == 'b':
        translated = translated + '22'
    elif t == 'c':
        translated = translated + '23'
    while n <= len(message):
        n = n + 1
print(translated)

It makes perfect sense to me so I had a hard time searching for appropriate help that solves for what I am doing, so can I have some help? A link, a solution, what I'm doing wrong and how to fix it? Thanks

Upvotes: 0

Views: 71

Answers (3)

SumanKalyan
SumanKalyan

Reputation: 1761

Because at last loop you are using t = message[3]..It is the cause of your error. If you message variable contain "abc" then you can access only t = message[0], t = message[1], t = message[2]. So try this

message = "abc"
#Should come out as 212223
translated = ' '


n = 1
while n >= 0:
    t = message[n-1]
    if t == 'a':
        translated = translated + '21'
    elif t == 'b':
        translated = translated + '22'
    elif t == 'c':
        translated = translated + '23'
    while n <= len(message):
        n = n + 1
print(translated)

Upvotes: 0

Zpooks
Zpooks

Reputation: 90

Here:

while n <= len(message):
    n = n + 1

Should need changing to:

while n < len(message):
    n = n + 1

The last index of a string will be len(message) - 1, as indexing starts at 0. I would just set n to len(message) - 1 instantly instead however.

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81594

n = 0
while n >= 0:

You have an infinite loop as you keep on incrementing n. At some point message[n] will get out of range.

You should move the while n <= len(message): to be your main loop instead of your current one.

A better way will be to iterate directly over message with a for loop:

for t in message:
    if t == 'a':
        translated = translated + '21'
    elif t == 'b':
        translated = translated + '22'
    elif t == 'c':
        translated = translated + '23'

Upvotes: 3

Related Questions