Here is my code for converting number into English words. Here I have one problem that I can't resolve it. If I input 0
, this should give me "zero"
. However, if I input any multiple of 10
, it will give me 'hundred zero'
rather than 'hundred'
.
If I remove if x == 0: return 'zero'
, this will give me 'zero'
if I input '0'
. Therefore, how should I be able to resolve this 'zero'
issue?
# Create a function that can spell out in English while inputting a whole number
def spelltowords(x):
digits_to_nineteen = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
decades = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
if x < 1000000000:
if x < 100000000:
if x < 20000000:
if x < 1000000:
if x < 100000:
if x < 20000:
if x < 1000:
if x < 100:
if x < 20:
if x is 0:
if x < 0:
return 'negative' + ' ' + spelltowords(-1*x)
return 'zero'
return digits_to_nineteen[x]
else:
return decades[x // 10] + ' ' + digits_to_nineteen[x % 10]
else:
return digits_to_nineteen[x // 100] + ' ' + 'hundred' + ' ' + spelltowords(x % 100)
else:
return digits_to_nineteen[x // 1000] + ' ' + 'thousand' + ' ' + spelltowords(x % 1000)
else:
return decades[(x // 1000) // 10] + ' ' + digits_to_nineteen[(x // 1000) % 10] + ' ' + 'thousand' + ' ' + spelltowords(x % 1000)
else:
return digits_to_nineteen[(x // 1000) // 100] + ' ' + 'hundred' + ' ' + spelltowords((x // 1000) % 100) + ' ' + 'thousand' + ' ' + spelltowords(x % 1000)
else:
return digits_to_nineteen[x // 1000000] + ' ' + 'million' + ' ' + spelltowords(x % 1000000)
else:
return decades[(x // 1000000) // 10] + ' ' + digits_to_nineteen[(x // 1000000) % 10] + ' ' + 'million' + ' ' + spelltowords(x % 1000000)
else:
return digits_to_nineteen[(x // 1000000) // 100] + ' ' + 'hundred' + ' ' + spelltowords((x // 1000000) % 100)+ ' ' + 'million' + ' ' + spelltowords(x % 1000000)
else:
return 'over the limit!'
print(spelltowords(200))
Output from the above code
>>> ================================ RESTART ================================
>>>
two hundred zero
>>>