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?
CodePudding user response:
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]
CodePudding user response:
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