Skip to content

Instantly share code, notes, and snippets.

@imxdn
Last active February 19, 2016 06:47
Show Gist options
  • Select an option

  • Save imxdn/617896205902f1e85015 to your computer and use it in GitHub Desktop.

Select an option

Save imxdn/617896205902f1e85015 to your computer and use it in GitHub Desktop.
A small Python program to convert an integer in range (0,9999) to its equivalent in words notation.
#
# Convert numbers to words. Not to be used to complete check books.
# @author : Aimad Ahsan
#
'''Primitives are unique words which are present when converting to
in word notation organized as a dictionary'''
primitives = {
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 : 'Nineteen',
20 : 'Twenty',
30 : 'Thirty',
40 : 'Forty',
50 : 'Fifty',
60 : 'Sixty',
70 : 'Seventy',
80 : 'Eighty',
90 : 'Ninety'
}
class ValueError(Exception):
pass
def wordify(number):
'''Converts a number to it equivalent word notation
Args:
number : Integer value (Between 0-9999)
Returns:
wordified : String of 'in words' notation
Raises:
ValueError : When an invalid integer or integer outside valid
range is passed as an argument
'''
#
# Disclaimer:
# Whereas integer division (//) could be used to obtain decimal
# places, what fun would that be? Right?
#
#
try:
s = str(number) # For slicing
wordified = '' # This will become the output string
except:
raise ValueError('NaN: Not a number')
if len(s)>=5:
raise ValueError('Range exceeded for number argument')
if len(s)==4 and int(s[-4:-3])!=0:
t = int(s[-4:-3])
wordified += '{} Thousand '.format(primitives[t])
if len(s)>=3 and int(s[-3:-2])!=0:
h = int(s[-3:-2])
wordified += '{} Hundred '.format(primitives[h])
if int(s[-2:])!=0:
ot = int(s[-2:])
if ot<20 or ot%10==0:
wordified += '{} '.format(primitives[ot])
else:
o = ot%10
t = ot-o
wordified += '{0} {1}'.format(primitives[t],primitives[o])
if number==0:
wordified += 'Zero'
return wordified
n = int(input('Enter a number: ').strip())
res = wordify(n)
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment