Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print Digit Word

Convert one digit to its English word with a Python list. Beginners practice zero-based indexing and validate a number before using it as a list position.

IntermediatePhase 1 - Level 4: Logical Operators & Compound StatementsExample 7 of 10
print-digit-word.py
1# Take digit
2digit = int(input("Enter a digit (0-9): "))
3
4# Map to word
5words = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
6
7if 0 <= digit <= 9:
8 print(words[digit])
9else:
10 print("Invalid digit")

Output

Enter a digit (0-9): 5
Five

Enter a digit (0-9): 0
Zero

In this one

  • Align digits with indexes
  • Validate before indexing
  • Understand negative indexes

How it works

  1. 1

    Create the ordered list of digit words.

  2. 2

    Check that digit lies from zero through nine.

  3. 3

    Print words[digit], otherwise report invalid input.

Edge cases

What does zero print?

What does zero print?

Zero, using list index zero.

Why reject -1 before indexing?

Why reject -1 before indexing?

Python would otherwise select the last item, Nine.

What's going on

The list stores ten words in digit order, starting with Zero at index zero. That deliberate alignment lets words[digit] act as a small lookup table.

Before indexing, the condition requires a value from zero through nine. Input 5 selects the sixth list entry, Five. The guard matters because negative indexes are valid Python syntax but would select words from the end instead of rejecting the digit.

What does zero print? Zero, using list index zero.

Why reject -1 before indexing? Python would otherwise select the last item, Nine.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which expression retrieves the word?

Pick an answer to check it.

Question 2

What does zero print?

Pick an answer to check it.

Questions people ask

What does zero print?

Zero, using list index zero.

Why reject -1 before indexing?

Python would otherwise select the last item, Nine.

Which expression retrieves the word?

words[digit].