To print a number in words

 def number_to_words(n):

# Define word lists up to 19, tens, and powers of 10 ones = ['zero', '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'] powers_of_10 = ['ones', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion', 'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion'] # Handle numbers from 0 to 19 if n < 20: return ones[n] # Handle numbers from 20 to 99 if n < 100: return tens[n // 10] + ('' if n % 10 == 0 else ' ' + ones[n % 10]) # Convert a number greater than or equal to 100 to words result = '' for i in range(len(powers_of_10)-1, -1, -1): p = 10 ** (3*i) if n >= p: millions = n // p n %= p if millions >= 100: result += ones[millions // 100] + ' hundred ' millions %= 100 if millions >= 20: result += tens[millions // 10] + ' ' + ones[millions % 10] elif millions > 0: result += ones[millions] result += ' ' + powers_of_10[i] return result.strip() # Test the function num = int(input("Enter a number: ")) words = number_to_words(num) print(f"{num} in words is: {words}") This program uses the number_to_words function which converts a given number into words. It handles numbers from 0 to vigintillion (1 followed by 63 zeros). After defining the word lists for ones, tens, and powers of 10, the function checks the number's value and processes it accordingly. It handles three-digit numbers, merging the words for hundreds, tens, and ones. For numbers greater than 999, it iterates through the powers_of_10 list to split the number into groups of three digits, converting each group to its word representation. Finally, it returns the words for the given number.

Comments

Popular posts from this blog

Ecommerce website

Yes, Python is an object-oriented programming (OOP) language, but it is also a multi-paradigm language

Your task is to find the missing number.