首页 > 解决方案 > IndexError: list index out of range: When try to display digits into English words

问题描述

I am new to learning programming and I tried to make a simple prg to display input digits into English upto 999, it works correctly till 99 but when it comes to 100's than i get following error: please help me to understand what I am doing wrong?

print('Print digits into english upto 999')
words_upto_ninteen=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Tweleve','Thirteen','Fourteen','Fifteen', 'Sixteen','Seventeen','Eighteen','Nineteen']

words_tens=['','','Twenty','Thirty','Fourty','Fifty','Sixty','Seventy','Eighty','Ninty']

words_hundreds=[' ','One Hundred','Two Hundred','Three Hundred','Four Hundred','Five Hundred','Six Hundred','Seven Hundred','Eight Hundred','Nine Hundred']

n=int(input("Please enter digits 0 to 999:"))
output=''
if n==0:
    output='zero'
elif n<=19:
    output=words_upto_ninteen[n]
elif n<=99:
    output=words_tens[n//10]+"  "+ words_upto_ninteen[n%10]
elif n<=999:
    output=words_hundreds[n//100]+" "+ words_tens[n//10]+" "+ words_upto_ninteen[n%10]

else:
    output=print('Please enter value upto 999')
print(output)
print('###########################################################################################')

Sample Output:

Please enter digits 0 to 999:433
Traceback (most recent call last):
  File "D:/python learning/projects/4flow control/rough2.py", line 21, in <module>
    output=words_hundreds[n//100]+" "+ words_tens[n//10]+" "+ words_upto_ninteen[n%10]
IndexError: list index out of range

标签: python-3.x

解决方案


This solution would work:

print('Print digits into english upto 999')
words_upto_ninteen=['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Tweleve','Thirteen','Fourteen','Fifteen', 'Sixteen','Seventeen','Eighteen','Nineteen']

words_tens=['','','Twenty','Thirty','Fourty','Fifty','Sixty','Seventy','Eighty','Ninty']

words_hundreds=[' ','One Hundred','Two Hundred','Three Hundred','Four Hundred','Five Hundred','Six Hundred','Seven Hundred','Eight Hundred','Nine Hundred']

n=int(input("Please enter digits 0 to 999:"))
output=''
if n==0:
    output='zero'
elif n<=19:
    output=words_upto_ninteen[n]
elif n<=99:
    output=words_tens[n//10]+"  "+ words_upto_ninteen[n%10]
elif n<=999:
    output=words_hundreds[n//100]+" "+ words_tens[(n//10)%10]+" "+ words_upto_ninteen[n%10]

else:
    output=print('Please enter value upto 999')
print(output)
print('###########################################################################################')

You made a mistake in words_ten[n//10] in fourth condition. Hope it helps :)


推荐阅读