user16072788
user16072788

Reputation:

Turn letters to number not working python

I have this code in python:

lettonum = {
  "a":1,
  "b":2,
  "c":3
}
def tonum(eput):
  output = ""
  doing = 1
  for _ in range(len(eput)):
    mys = lettonum[eput[doing]]
    output = f"{output}{mys}"
    doing = doing + 1
  print(output)

while True:
  tonum(input("String to be encoded to numbers: "))

Basically, it is supposed to turn letters a, b, and c to numbers 1, 2, and 3

I put in

String to be encoded to numbers: abc

but it throws this error

Traceback (most recent call last):
  File "main.py", line 19, in <module>
    tonum(input("String to be encoded to numbers: "))
  File "main.py", line 13, in tonum
    mys = lettonum[eput[doing]]
IndexError: string index out of range

What's wrong?

Upvotes: 1

Views: 60

Answers (3)

Mark
Mark

Reputation: 92471

Python discourages looping over ranges unless you really need the indices. Doing for index in range(len(something)): then something[index] is a waste when python lets you more easily just iterate over the values directly. One of the main advantages of this is that you avoid the very common indexing problems you are experiencing:

lettonum = {
    "a":1,
    "b":2,
    "c":3
}

def tonum(eput):
    output = ""
    for letter in eput:
        mys = lettonum[letter]
        output += str(mys)
    print(output)


tonum('abc')
# 123

Upvotes: 1

guest
guest

Reputation: 1

Indexes start from 0, not 1.

lettonum = {
  "a":1,
  "b":2,
  "c":3
}
def tonum(eput):
  output = ""
  doing = 1
  for _ in range(len(eput)):
    mys = lettonum[eput[doing]]
    output = f"{output}{mys}"
    doing = doing + 1
  print(output)

while True:
  tonum(input("String to be encoded to numbers: "))

Upvotes: 0

Oleksii Tambovtsev
Oleksii Tambovtsev

Reputation: 2834

You should start indexing from 0, not 1:

lettonum = {
  "a": 1,
  "b": 2,
  "c": 3
}


def tonum(eput):
    global lettonum
    output = ""
    doing = 0
    for _ in range(len(eput)):
        mys = lettonum[eput[doing]]
        output = f"{output}{mys}"
        doing = doing + 1
    print(output)


while True:
    tonum(input("String to be encoded to numbers: "))

Or alternative (and better) solution with indexing:

def tonum(eput):
    global lettonum
    output = ""
    for doing in range(len(eput)):
        mys = lettonum[eput[doing]]
        output = f"{output}{mys}"
    print(output)

Upvotes: 0

Related Questions