Python program to covert a number into words (Up to 1 lakh)


def number_to_words(num):
    ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
    tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
    teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
    if num == 0:
        return 'zero'
    elif num < 0:
        return 'minus ' + number_to_words(abs(num))
    else:
        if num < 10:
            return ones[num]
        elif num < 20:
            return teens[num-10]
        elif num < 100:
            return tens[num//10] + ('' if num % 10 == 0 else ' ' + ones[num % 10])
        elif num < 1000:
            return ones[num//100] + ' hundred' + (' and ' + number_to_words(num % 100) if num % 100 != 0 else '')
        elif num < 100000:
            return number_to_words(num//1000) + ' thousand' + (' ' + number_to_words(num % 1000) if num % 1000 != 0 else '')
        else:
            return 'Number out of range'

# Take user input
num = int(input('Enter a number up to one lakh: '))

# Convert number to words and print the result
print(number_to_words(num))

Post a Comment

1 Comments


  1. def number_to_words(num):
    ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
    tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
    teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
    if num == 0:
    return 'zero'
    elif num < 0:
    return 'minus ' + number_to_words(abs(num))
    else:
    if num < 10:
    return ones[num]
    elif num < 20:
    return teens[num-10]
    elif num < 100:
    return tens[num//10] + ('' if num % 10 == 0 else ' ' + ones[num % 10])
    elif num < 1000:
    return ones[num//100] + ' hundred' + (' and ' + number_to_words(num % 100) if num % 100 != 0 else '')
    elif num < 100000:
    return number_to_words(num//1000) + ' thousand' + (' ' + number_to_words(num % 1000) if num % 1000 != 0 else '')
    else:
    return 'Number out of range'

    # Take user input
    num = int(input('Enter a number up to one lakh: '))

    # Convert number to words and print the result
    print(number_to_words(num))

    ReplyDelete