Create a program in Python to convert any number from 0 to 999 to its corresponding…
- User
Create a program in Python to convert any number from 0 to 999 to its corresponding word. Input number: 259
Assistant
Create a program in Python to convert any number from 0 to 999 to its corresponding word. Input number: 259
Input: An integer (e.g., 259).
Output: A string (e.g., "two hundred fifty-nine").
Logic:
Drafting the Code:
ones = ["", "one", "two", ... "nineteen"] (handling 0-19 implies ones and teens).tens = ["", "", "twenty", "thirty", ... "ninety"].convert_to_words(num):
num == 0: return "zero".result = ""num >= 100: result += ones[num//100] + " hundred", num %= 100.num > 0:
result is not empty, add space? Actually, standard formatting usually puts "and" (UK) or just space (US). The prompt is generic, so I will use a space or "and". Let's stick to standard simple US English: "two hundred fifty-nine".num < 20: result += " " + ones[num]result += " " + tens[num//10]. If num % 10 > 0: result += "-" + ones[num % 10].Refined Code Structure:
Here is the Python program to solve the problem.
def number_to_words(num):
# Define word lists for mapping
# Index 0 is empty string for easier mapping, though 0 is handled separately
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen"]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
# Handle the 0 case explicitly
if num == 0:
return "zero"
# Check for valid input range
if num < 0 or num > 999:
return "Number out of range (0-999)"
parts = []
# Handle Hundreds place
if num >= 100:
hundred_digit = num // 100
parts.append(ones[hundred_digit] + " hundred")
num %= 100 # Get the remainder (tens and ones)
# Handle Tens and Ones places
if num > 0:
# If there was a hundred part, we might add a separator here if desired,
# but standard English usually just uses a space or "and".
# We will simply append to the list and join with a space later.
if num < 20:
# Numbers 1-19 are direct mappings from the ones list
parts.append(ones[num])
else:
# Numbers 20-99
ten_digit = num // 10
one_digit = num % 10
if one_digit == 0:
parts.append(tens[ten_digit])
else:
# Hyphenate compound numbers like twenty-one
parts.append(tens[ten_digit] + "-" + ones[one_digit])
# Join the parts with a space
return " ".join(parts)
# Main execution
if __name__ == "__main__":
try:
user_input = int(input("Input number: "))
result = number_to_words(user_input)
print(f"Output: {result}")
except ValueError:
print("Please enter a vali