2
diction = {
    0 : "zero",
    1 : "one",
    2 : "two",
    3 : "three",
    4 : "four",
    5 : "five",
    6 : "six",
    7 : "seven",
    8 : "eight",
    9 : "nine",
    }
n = int(input("Input a number: "))
print (diction[n])

this is my code but it only works if i input a single digit number. It returns an error when inputted more than 1 digit. How do I solve that?

5 Answers 5

5

You need to iterate over the inputted number, one number at a time, and look it up in your dict:

diction = {
    0 : "zero",
    1 : "one",
    2 : "two",
    3 : "three",
    4 : "four",
    5 : "five",
    6 : "six",
    7 : "seven",
    8 : "eight",
    9 : "nine",
}
n = int(input("Input a number: "))
print (' '.join(diction[int(x)] for x in str(n)))

Note that since you have to iterate over a string, and then convert it back to int to look up in the dict, it might be easier to store the keys int he dict as string.

EDIT: If you want to get the full English name for a number, e.g. 465 is four hundred and sixty five, you might want to look at the inflect package.

2
  • May as well keep n as a string rather than convert back and forth Commented Feb 21, 2018 at 9:46
  • Yep - I say that after the code block (didn't explicitly make this change though, in case OP has a reason to use ints as keys).
    – match
    Commented Feb 21, 2018 at 9:57
4
diction = {
    0 : "zero",
    1 : "one",
    2 : "two",
    3 : "three",
    4 : "four",
    5 : "five",
    6 : "six",
    7 : "seven",
    8 : "eight",
    9 : "nine",
    }

n = int(input("Input a number: "))
for i in str(n):
  print (diction[int(i)])
1
  • you can use print (diction[int(i)],end=' ') also to get output in one line Commented Feb 21, 2018 at 9:40
1

This is one way. toolz.compose is useful for processing multiple functions on an interable. You may also see a small performance improvement versus a generation expression.

from toolz import compose

diction = {
    0 : "zero",
    1 : "one",
    2 : "two",
    3 : "three",
    4 : "four",
    5 : "five",
    6 : "six",
    7 : "seven",
    8 : "eight",
    9 : "nine",
    }

n = input("Input a number: ")

print(' '.join(map(compose(diction.get, int), list(n))))
0

If you want to go full ninja:

# pip install inflect
import inflect
p = inflect.engine()

print (' '.join(p.number_to_words(x) for x in input("Input a number: ")))

No variables, just code.

Always look for available packages when solving already solved problems. Your assignment seemed school like, and I'd argue its more use in a teaching environment to teach students how to use packages...

0

Just use:

ints = map(int, str(n)) #if you dont convert input its easier!
dictions = map(diction.get, ints)
result = ' '.join(dictions)
print(result)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.