题目:使用列表,编写将0~1000范围的数字翻译为英文的程序,例如输入89,输出eighty-nine。
-
#!/usr/bin/env python
-
'''numbers to english'''
-
-
#for less than 21
-
list1=['zero','one','two','three','four','five','six','seven','eight','nine',
-
'ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen',
-
'seventeen','eighteen','nineteen','twenty']
-
#for second bit
-
list2=['','','twenty','thirty','forty','fifty',
-
'sixty','seventy','eighty','ninety','hundred']
-
#for 1000
-
list3=['','one thousand']
-
-
#filter th input
-
def num_input():
-
while True:
-
num=raw_input('Enter a number in 0~1000: ')
-
num=num.strip()
-
if num=='':
-
print 'no value'
-
continue
-
try:
-
num2=int(num)
-
except Exception:
-
print 'TypeError'
-
continue
-
if num2<0 or num2>1000:
-
print 'over range'
-
else:
-
break
-
return num
-
-
#translate number to english
-
def translate(num):
-
n1=int(num)
-
if n1<21 and n1>=0: #one word
-
r1=list1[n1] #use index
-
return r1
-
elif n1>20 and n1<100: #use second bit
-
n2=repr(n1) #to string
-
r2=list2[int(n2[-2])] #the second bit
-
r3=list1[int(n2[-1])] #the first bit
-
if int(n2[-1])==0: #only second bit and first bit is 0
-
return r2
-
else:
-
return r2+'-'+r3
-
elif n1>=100 and n1<1000: #use third bit
-
n3=repr(n1)
-
r4=list1[int(n3[-3])] #the third bit
-
r5=list2[int(n3[-2])] #the second bit
-
r6=list1[int(n3[-1])] #the first bit
-
if int(n3[-1])==0 and int(n3[-2])!=1: #first is 0
-
return r4+' hundred-'+r5
-
elif int(n3[-2])==1:
-
r7=list1[int(n3[-2:])] #sec+fir less than 20,only use list1
-
return r4+' hundred-'+r7
-
else:
-
return r4+' hundred-'+r5+'-'+r6
-
elif n1==1000:
-
r8=list3[1] #use fourth
-
return r8
-
-
if __name__=='__main__': #main()
-
print translate(num_input())
测试记录:
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: 0
zero
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: 1
one
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: 13
thirteen
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: 311
three hundred-eleven
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: 721
seven hundred-twenty-one
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: 899
eight hundred-ninety-nine
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: 1000
one thousand
[root@ahqz py]# python num-to-english.py
Enter a number in 0~1000: a
TypeError
Enter a number in 0~1000: b
TypeError
Enter a number in 0~1000:
no value
Enter a number in 0~1000: 666
six hundred-sixty-six
[root@ahqz py]#
阅读(965) | 评论(0) | 转发(0) |