Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to write a function, which will accept parameter and it will print with a condition (It's output will depend on the input). My program is giving key error. I am looking for an output like:
This number is less than 0 and it's spelling is one hundred
thirteen
and my code is: <pre>
def word(num):
   d1= {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:'Fourty',50:'Fifty',60:'Sixty',70:'Seventy',80:'Eighty',90:'Ninty'}

   if (num<20):
      return d1[num]
   if (num<100):
      if num % 10 == 0:
         return d1[num]  
      else:
         return d1[num // 10 * 10] + ' ' + d1[num % 10]
   if (num < 0):
      return "This number is less than 0 and it's spelling is" + word(num)

print (word(- 100))
print (word(13))


What I have tried:

I have tried to write ,
if (num < 0):
under the d1 line, but I got error saying, "recursion error: maximum recursion depth exceeded in comparison".
Posted
Updated 5-Feb-19 21:59pm

If you feed your method a negative value then your condition takes effect - and you call your function again with exactly the same parameter value!
So what happens? The value is still negative, so the condition is still true, so you do the same thing again. The solution is simple: don't pass the same value! If it's a negative number, pass the positive version instead:
PHP
if (num < 0):
   return "This number is less than 0 and it's spelling is" + word(-num)
And next time, it's positive and will work normally.
 
Share this answer
 
Following Griff's wise suggestion...
Try
Python
def word(num):
  d1= {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:'Fourty',50:'Fifty',60:'Sixty',70:'Seventy',80:'Eighty',90:'Ninty'}

  if num >= 100 or num <= -100:
    return "This number is out of range"
  elif num < 0:
    return "This number is less than 0 and it's spelling is Minus " + word(-num)
  elif num < 20:
    return d1[num]
  else:
    if num % 10 == 0:
      return d1[num]
    else:
      return d1[num // 10 * 10] + ' ' + d1[num % 10]



print (word(- 100))
print (word(- 42))
print (word(13))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900