0

I am struggeling with following:

"I am going to write a function - single parameter - which can be a number from 1 to 10. depending on this parameter, it should return the text of the number entered. if the parameter is 1, the function should set the text "one", if the parameter is two it should return "two" and so on."

How do I get this to become a for loop?

def numberToText(input): 
   if input == 1:
      return "one"
   if input == 2: 
      return "two"
return input

print(numberToText(input))
  • There are [packages](https://stackoverflow.com/questions/8982163/how-do-i-tell-python-to-convert-integers-into-words) that can do that for you. What you're asking also doesn't require a loop. It takes an input and returns an output. At no point does it have to iterate over anything. Though I guess pedantically you could do `for value, text in ((1, 'one'), (2, 'two'),...): if value == input: return text` – Reti43 Nov 22 '21 at 00:42

1 Answers1

1

You can use a Dictionary to store your 10 numbers, and then quickly reference it by index to return the number it equals to, or None if it doesn't exist - this way, you don't need to write 10 different conditional statements.

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

def numberToText(input):
    return numberTable.get(input, None)
Skully
  • 2,882
  • 3
  • 20
  • 31