Home > Blockchain >  Turn letters to number not working python
Turn letters to number not working python

Time:01-24

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?

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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: "))
  •  Tags:  
  • Related