未转换为字符串的数字

2024-06-25 23:51:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序打印到99,但在99之后,输入不会转换为文字,即
如果我把450作为输入,那么这就是给定的错误。请帮我做这个

words_upto_19=['','one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 
 'ten', 'eleven' , 'twelve' , 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 
 'nineteen']

words_upto_tens =['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']
words_upto_999=['hundred and ']

a=int(input('enter the no. between 1 and 100:'))
if a==0:
    output='zero'

#for converting numbers above 1 till 19 into words.
elif a<=19:
    output=words_upto_19[a]

#for converting numbers above 20 till 99 into words.
elif a<=99:
    output= words_upto_tens[a//10] +" "+words_upto_19[a%10]

#for converting numbers above 99 till 999 into words.
elif a<=999:
    output=words_upto_999[a//100]+''+ words_upto_tens[a//10] +''+words_upto_19[a%10]
    
else:
    output='please enter the no. between 1 to 100'

print(output)

Tags: andthenoforoutputabovewordsenter
1条回答
网友
1楼 · 发布于 2024-06-25 23:51:31

a <=999的逻辑错误

  1. 如果输入是450,a//100将是4,但words_upto_999列表只有一个元素。因此,words_upto_999[a//100]将引发一个异常

    您可以使用words_upto_19[a//100] + " hundred and " + ...获得百的倍数。你也可以摆脱words_upto_999

  2. 对于下一部分(即words_upto_tens[a//10]),您也需要更改它。假设对于相同的输入450a//10变为45words_upto_tens[a//10]将再次引发异常。您可以改用words_upto_tens[(a%100)//10]

因此,该块的代码可以是-

elif a<=999:
    output=words_upto_19[a//100] + ' hundred and ' + words_upto_tens[(a%100)//10] + ' ' + words_upto_19[a%10]

同样,它也不是完全正确的数字>;第二位数字为1的100(例如311、519等)将无法正确打印。但我想你可以自己解决

相关问题 更多 >