正确 | 10 | 58 | 27412 |
2-1019 长度转换程序(10分)
完善下面的程序,能够:
(1) 将用户输入的公制长度单位(米、千米)转换成英制长度单位(英寸、英里);
(2) 将用户输入的英制长度单位(英寸、英里)转换成公制长度单位(米、千米);
(3) 将转换结果输出到屏幕上。
提示:
长度单位:1 英寸=2.5400 厘米 1 英里 =1.6093 千米
这是老师的程序,在前面输入都是合法数值的时候能正确运行,请完善, 保证前面任意输入的情况下都能正确处理
length=raw_input()
if length[-4:] in ['Inch','INCH','inch']:
l=eval(length[0:-4])*0.0254
print 'The length is %fm' %l
elif length[-4:] in ['mile','Mile','MILE']:
l=eval(length[0:-4])*1.6093
print 'The length is %fkm' %l
elif length[-2:] in ['km','KM','Km']:
l=eval(length[0:-2])/1.6093
print 'The length is %fmile' %l
elif length[-1] in ['m','M']:
l=eval(length[0:-1])/0.0254
print 'The length is %finch' %l
else:
print 'Error'
输入格式:
输入数量及单位,例如:1inch
或者输入一串非法字符串,例如:111asdkfljlka123156sdinch
输出格式:
输出提示及结果,例如:The length is 0.025400m,注意小数位数和空格的位置
如果遇到非法字符串,则输出:Error
主要是判断非法字符
length=raw_input()
if length[-4:] in ['Inch','INCH','inch']:
if(length[0:-4].isdigit()==True):
l=eval(length[0:-4])*0.0254
print 'The length is %fm' %l
else:
print'Error'
elif length[-4:] in ['mile','Mile','MILE']:
if(length[0:-4].isdigit()==True):
l=eval(length[0:-4])*1.6093
print 'The length is %fkm' %l
else:
print'Error'
elif length[-2:] in ['km','KM','Km']:
if(length[0:-2].isdigit()==True):
l=eval(length[0:-2])/1.6093
print 'The length is %fmile' %l
else:
print'Error'
elif length[-1] in ['m','M']:
if(length[0:-1].isdigit()==True):
l=eval(length[0:-1])/0.0254
print 'The length is %finch' %l
else:
print'error'
else:
print 'Error'