Reputation: 1
I have an assignment to write code to print a number in words. I'm new to coding, so please do not judge my code... . so ive written the code am fairly certain it should work, but it isnt producing an output. there's no syntax error apparently either. Please advice. If theres a better code please let me know as well but i would like to know why my code doesnt work
This is the code:
x=0
Dictcom= {1:'One ',2:'Two ',3:'Three ',4:'Four ',5:'Five ',6:'Six ',7:'Seven ',8:'Eight ',9:'Nine '}
Placename={2:'Hundred ',3:'Thousand ',5:'Hundred ',6:'Million ',8:'Hundred ',9:'Billion '}
Ortyplanename={2:'Twenty ',3:'Thirty ',4:'Forty ',5:'Fifty ',6:'Sixty ',7:'Seventy ',8:'Eighty ',9:'Ninety '}
OnesTensCase={10:'Ten ',11:'Eleven ',12:'Twelve ',13:'Thirteen ',14:'Fourteen ',15:'Fifteen ',16:'Sixteen ',17:'Seventeen '
,18:'Eighteen ',19:'Nineteen '}
n=input("Enter a number less than 11 digits: ")
x=y=0
S=''
for i in n:
x+=1
n=int(n)
while x>(-1):
y=n//10**(x-1)
if y==0:
continue
elif x==2 or x==5 or x==8:
n=str(n)
if n[0:2] in OnesTensCase:
S+=OnesTensCase[n[0:2]]
elif y in Ortyplanename:
S+=Ortyplanename[y]
else:
if y!=0:
str(y)
S+=Dictcom[y]
if (x-1) in Placename:
S+=Placename[x-1]
if x!=0:
S+="And "
n=int(n)
n=n%10**(x-1)
x-=1
print(S)
Upvotes: 0
Views: 72
Reputation: 6857
The reason for the infinite loop that is preventing your output from displaying, is that on the very last loop iteration, the following line will set y
to 0
:
y=n//10**(x-1)
And since right after that you have the following:
if y==0:
continue
That means your code will infinitely loop on the last loop iteration. This is because on the last loop iteration, the value of x
is 0
, and the value of n
is 0
, and so 0//10**(0-1)
will obviously equal zero.
Otherwise though your code works okay. I put in the number 123456789
and the text representation was accurate except there were too many "And"
s, but I know that's unrelated to your question:
One Hundred And Twenty Three Million And Four Hundred And Fifty Six Thousand And Seven Hundred And Eighty Nine
Upvotes: 2