Python function which accept number as input and return it in words
Exercises for Python| User defined function in Python| Function accept number return in words| Exercises for Python List, String, functions and operators
ICT A/L
#function defined to accept two digit number as parameter and print the number in words
def digit1n2rword(num):
ones = ["Zero", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine"]
teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
if num < 10:
return ones[num]
elif num < 20:
return teens[num - 10]
else:
return tens[num // 10] + (" " + ones[num % 10] if num % 10 != 0 else "")
#function defined to accept three digit number as parameter and print the number in words using the digit1n2rword
def digit3word(num):
if num < 100:
return digit1n2rword(num)
hundreds = num // 100
remainder = num % 100
if remainder == 0:
return digit1n2rword(hundreds) + " Hundred"
else:
return digit1n2rword(hundreds) + " Hundred " + digit1n2rword(remainder)
#function defined to accept any digit number as parameter and print the number in words using the function digit3word
def anyDigitWord(num):
if num == 0:
print("Zero")
return
place_values = ["", "Thousand", "Million", "Billion", "Trillion"]
words = []
i = 0
while num > 0:
part = num % 1000
if part != 0:
text = digit3word(part)
if place_values[i]:
text += " " + place_values[i]
words.insert(0, text)
num //= 1000
i += 1
print(" ".join(words))
Main Program which call the anyDigitWord function with given numbers
anyDigitWord(7)
anyDigitWord(19)
anyDigitWord(56)
anyDigitWord(105)
anyDigitWord(250)
anyDigitWord(123456786)
Output
Seven
Nineteen
Fifty Six
One Hundred Five
Two Hundred Fifty
One Hundred Twenty Three Million Four Hundred Fifty Six Thousand Seven Hundred Eighty Six
No comments:
Post a Comment