def translate_digit(digit): """ Return the translated digit. """ if digit == 1: return 'one' elif digit == 2: return 'two' elif digit == 3: return 'three' elif digit == 4: return 'four' elif digit == 5: return 'five' elif digit == 6: return 'six' elif digit == 7: return 'seven' elif digit == 8: return 'eight' else: return 'nine' def translate_teens(digit): """ Return the translated teens digit. """ if digit == 0: return 'ten' elif digit == 1: return 'eleven' elif digit == 2: return 'twelve' elif digit == 3: return 'thirteen' elif digit == 4: return 'fourteen' elif digit == 5: return 'fifteen' elif digit == 6: return 'sixtern' elif digit == 7: return 'seventeen' elif digit == 8: return 'eighteen' elif digit == 9: return 'nineteen' def translate_tens_digit(digit): """ Return the translated tens digit. """ if digit == 2: return 'twenty' elif digit == 3: return 'thirty' elif digit == 4: return 'forty' elif digit == 5: return 'fifty' elif digit == 6: return 'sixty' elif digit == 7: return 'seventy' elif digit == 8: return 'eighty' elif digit == 9: return 'ninety' def translate_pair(pair): """ Return the translation of a pair digits """ tens_digit = pair // 10 ones_digit = pair % 10 if (tens_digit == 0) and (ones_digit > 0): str = translate_digit(ones_digit) elif tens_digit == 1: str = translate_teens(ones_digit) elif tens_digit != 0: str = translate_tens_digit(tens_digit) # Append a hyphen and the ones word. if ones_digit > 0: str += '-' + translate_digit(ones_digit) else: str = '' return str def translate_triplet(triplet): """ Return the translation of a triplet. """ str = ''; # Break apart triplet into a hundreds digit # and the remaining pair of digits. hundreds_digit = triplet//100 pair = triplet % 100 if hundreds_digit > 0: str = translate_digit(hundreds_digit) + ' hundred' if pair > 0: str += ' ' + translate_pair(pair) return str def translate(n): """ Return the translation of a number. """ str = ''; # Break apart n into three triplets. millions = n//1_000_000 remainder = n%1_000_000 thousands = remainder//1000 hundreds = remainder%1000 if millions > 0: str += translate_triplet(millions) + ' million' if thousands > 0: if millions > 0: str += ' ' str += translate_triplet(thousands) + ' thousand' if hundreds > 0: if (millions > 0) or (thousands > 0): str += ' ' str += translate_triplet(hundreds) return str; def prompt_for_number(): """ Prompt the user for a number and return its value. """ good_number = False while not good_number: number = int(input('Number to translate? ')) good_number = (0 <= number <= 999_999_999) if not good_number: print('Number must be between 1 and 999,999,999 inclusive. 0 to stop.') print() return number n = prompt_for_number() # Loop to prompt for and translate numbers # until the user enters 0. while n > 0: print(translate(n)) print() n = prompt_for_number() print() print('Done!')