0

Is there a nice way to write code so that if someone type in the int 1 I want to return the string "one" and if they type 2 return "two" and so on.

it does not have to be infinity

I was thinking to have 2 lists:

[1, 2, 3, 4, 5, 6]

["one", "two, "three", "four", "five", "six"]

and the somehow loop through them.

Instead of having to write:

if input == 1:
    return "one"
elif input == 2:
    return "two"

an so on.....

Someone have a nicer way maybe?

MVB
  • 45
  • 4
  • 1
    You could use a `dictionary` instead of using two lists – BoredRyuzaki Jan 22 '22 at 15:33
  • 1
    What's the max number you need to support? This is a trivial task for numbers up to 10-20, then it begins to get more difficult. For number less than 10-20, you could use a dictionary to map integers to strings. To support larger numbers, you'd either have a ton of manual writing to do, or you'd need to create an algorithm to generate the strings based on the numbers, and that can be a tricky task. – Carcigenicate Jan 22 '22 at 15:34
  • 3
    Does this answer your question? [How do I tell Python to convert integers into words](https://stackoverflow.com/questions/8982163/how-do-i-tell-python-to-convert-integers-into-words) – Jordan Gillard Jan 22 '22 at 15:36
  • oh thanks that was a more DRY, perfect – MVB Jan 22 '22 at 15:38

2 Answers2

0

You can use a dictionary

number = int(input())
number_dictionary = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six"}
return number_dicionary[number]
BoredRyuzaki
  • 163
  • 2
  • 10
0

One solution is to make a list and then used the passed integer as the index

numbers = ["zero", "one", "two", "three", "four", "five", "six"]
return numbers[input]

I highly encourage you not to use the word input as a variable name, as it shadows the built-in name for Python's input function.

There is also the open-source inflect library on pypi.

>>>import inflect
>>>p = inflect.engine()
>>>p.number_to_words(99)
ninety-nine
Jordan Gillard
  • 301
  • 1
  • 5
  • 14