Anayatc Anayatc - 3 months ago 9
Python Question

add exceptions to python function

I have a function that takes an integer as input and returns the number as words, it works as I want with the exception of

30,40,50,60,70,80
and
90
, it returns for
90 = ninty zero
, because the function works by splitting the number, how can I remove the zero being added for the above numbers. my code is as follows

d = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five',
6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten',
11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen',
15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen',
19: 'ninteen', 20: 'twenty',
30: 'thirty', 40: 'fourth', 50: 'fifty', 60: 'sixty',
70: 'seventy', 80: 'eighty', 90: 'ninty'}

def wordify(n):
k = 1000
m = k * 1000
if n < 20:
return d[n]
if n < 100:
if n % 100 == 0: return d[n]
else: return d[n // 10 * 10] + ' ' + d[n % 10]
if n < k:
if n % 100 == 0: return d[n // 100] + ' hundred'
else: return d[n // 100] + ' hundred ' + wordify(n % 100)
if n < m:
if n % k == 0: return wordify(n // k) + ' thousand'
else: return wordify(n // k) + ' thousand, ' + wordify(n % k)


print wordify(90)

Answer

Changing the following line:

if n % 100 == 0: return d[n]

to

if n % 10 == 0: return d[n]

solves this issue. Since it will then always use the single word and not add the zero behind it whenever it's a multiple of 10.