I didn't take the time to comment this out so if you want the logic explained just shoot me a reply. It could probably be done in an easier way, but I'm only one semester into my CS degree. This was a fun problem!
def main():
again = 'y'
while again.lower() == 'y':
number = int(input("Enter a number: "))
print("In word format, that's", change_to_string(number) + '.')
again = input("Do you have another number? [y/n]: ")
def change_to_string(number):
place_list = format(number, ',d').split(',')
string_list = []
for place in place_list:
if len(place) == 3:
string_list.append(str_ben(place))
elif len(place) == 2:
string_list.append(str_ten(place))
elif len(place) == 1:
string_list.append(str_one(place))
num_string = get_num_string(string_list)
return num_string
def str_ben(number):
str_num = ''
if number[0] == '0':
str_num = ''
elif number[1:] == '00':
str_num += str_one(number[0]) + ' hundred'
else:
str_num += str_one(number[0]) + ' hundred and ' + str_ten(number[1:])
return str_num
def str_ten(number):
str_num = ''
tens = int(number[0])
ones = int(number[1])
if tens == 0:
str_num += str_one(ones)
elif tens == 1:
if ones == 0:
str_num += 'ten'
elif ones == 1:
str_num += 'eleven'
elif ones == 2:
str_num += 'twelve'
elif ones == 3:
str_num += 'thirteen'
elif ones == 4:
str_num += 'fourteen'
elif ones == 5:
str_num += 'fifteen'
elif ones == 6:
str_num += 'sixteen'
elif ones == 7:
str_num += 'seventeen'
elif ones == 8:
str_num += 'eighteen'
elif ones == 9:
str_num += 'nineteen'
elif tens == 2:
if ones == 0:
str_num += 'twenty'
else:
str_num += 'twenty ' + str_one(ones)
elif tens == 3:
if ones == 0:
str_num += 'thirty'
else:
str_num += 'thirty ' + str_one(ones)
elif tens == 4:
if ones == 0:
str_num += 'forty'
else:
str_num += 'forty ' + str_one(ones)
elif tens == 5:
if ones == 0:
str_num += 'fifty'
else:
str_num += 'fifty ' + str_one(ones)
elif tens == 6:
if ones == 0:
str_num += 'sixty'
else:
str_num += 'sixty ' + str_one(ones)
elif tens == 7:
if ones == 0:
str_num += 'seventy'
else:
str_num += 'seventy ' + str_one(ones)
elif tens == 8:
if ones == 0:
str_num += 'eighty'
else:
str_num += 'eighty ' + str_one(ones)
elif tens == 9:
if ones == 0:
str_num += 'ninety'
else:
str_num += 'ninety ' + str_one(ones)
return str_num
def str_one(number):
num = int(number)
if num == 0:
string = ''
elif num == 1:
string = 'one'
elif num == 2:
string = 'two'
elif num == 3:
string = 'three'
elif num == 4:
string = 'four'
elif num == 5:
string = 'five'
elif num == 6:
string = 'six'
elif num == 7:
string = 'seven'
elif num == 8:
string = 'eight'
elif num == 9:
string = 'nine'
return string
def get_num_string(string_list):
string = ''
place = len(string_list)
if place == 1:
string += string_list[0]
else:
for value in string_list:
string += value
if place == 4 and value != '':
string += ' billion '
elif place == 3 and value != '':
string += ' million '
elif place == 2 and value != '':
string += ' thousand '
place -= 1
return string.rstrip()
main()