《python核心编程第二版》第五章的一道课后练习题:
5-6 算术。
N1 运算符 N2. 其中 N1 和 N2 为整数或浮点数,运算符可以是+, -, , /, %, * 分别表示
加法,减法, 乘法, 整数除,取余和幂运算。计算这个表达式的结果,然后显示出来。提示:
可以使用字符串方法 split(),但不可以使用内建函数 eval().
我写的:
#!/usr/bin/env python
commandlist=[‘+’,’-‘,’‘,’/‘,’%’,’**’]
def getinput():
print ‘example: 4 + 7 , 6 / 3 ‘
input=raw_input(‘enter >>>’)
if input==’’:
return getinput()
else:
try:
input=input.split(‘ ‘)
except:
print ‘input error 1,must have blank’
return getinput()
else:
if len(input)!=3:
print ‘input error 2,must be three str’
return getinput()
else:
try:
a,b=int(input[0]),int(input[2])
except:
print ‘input error 3: must be number’
return getinput()
else:
if input[1] not in commandlist:
print ‘input error 4: unknown str’
return getinput()
else:
if input[1]==’+’:
return a,1,b
elif input[1]==’-‘:
return a,2,b
elif input[1]==’‘:
return a,3,b
elif input[1]==’/‘:
if b==0:
print ‘input error 5: integer division canot be zero’
return getinput()
else:
return a,4,b
elif input[1]==’%’:
if b==0:
print ‘input error 5: integer division canot be zero’
return getinput()
else:
return a,5,b
else:
return a,6,b
while True:
ans=raw_input(‘enter anything or q to quit’)
if ans==’q’:
break
else:
com=getinput()
if com[1]==1:
print ‘%d + %d = %d’%(com[0],com[2],com[0]+com[2])
elif com[1]==2:
print ‘%d - %d = %d’%(com[0],com[2],com[0]-com[2])
elif com[1]==3:
print ‘%d %d = %d’%(com[0],com[2],com[0]com[2])
elif com[1]==4:
print ‘%d / %d = %d’%(com[0],com[2],com[0]/com[2])
elif com[1]==5:
print ‘%d %% %d = %d’%(com[0],com[2],com[0]%com[2])
else:
print ‘%d %d = %d’%(com[0],com[2],com[0]com[2])
截图: