Skip to content
Programs · Program 10-8

Q.Program 10-8: Write a function to convert a number entered by the user into its corresponding number in words. For example, if the input is 876 then the output should be ‘Eight Seven Six’.

Rajasthan RbseTextbookSubjective· 3mImportance★★★★★est
40% · 12/30 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Treat the input as a string, look each digit up in a 0-9 digit-to-word dictionary, and concatenate the words — 876 becomes 'Eight Seven Six'.

The idea. The mapping digit -> word is fixed and small, which is exactly what a dictionary literal is for. The subtle design choice is to not convert the input to int: keeping num as a string lets us iterate over it character by character, and each character is turned into the integer key with int(ch). This also preserves leading zeros (int('076') would lose the 0).

Program 10-8:

def convert(num):
    numberNames = {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four',
                   5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}
    result = ''
    for ch in num:                       # num is a string, so we can loop over digits
        result = result + numberNames[int(ch)] + ' '
    return result.strip()

num = input("Enter any number: ")
print("The number is:", num)
print("The number in words is:", convert(num))

Sample run:

Enter any number: 876
The number is: 876
The number in words is: Eight Seven Six

Trace for input '876':

| ch | int(ch) | numberNames lookup | result so far |

|-----|---------|--------------------|----------------------| …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.