我写的计算器脚本:
print('计算器')
while True:
a=int(input('请输入第一个数字:'))
b=str(input('请输入运算符号:'))
c=int(input('请输入第二个数字:'))
if b == '+':
print('等于:',a+c)
elif b == '-':
print('等于:',a-c)
elif b == '*':
print('等于:',a*c)
elif b == '/':
print('等于:',a/c)
else:
print('错误')
只能计算两个数的结果,请问怎么改成多个数字运算的?
换个思路,轻松写意。
>>> while True:
exp = input('请输入算式:')
if exp == '' or exp == 'bye':
break
try:
result = eval(exp)
except:
print('算式错误,请重新输入。')
if isinstance(result, int):
print('%s = %d'%(exp, result))
else:
print('%s = %f'%(exp, result))
请输入算式:3+5*4
3+5*4 = 23
请输入算式:(3+5)*4
(3+5)*4 = 32
请输入算式:3/2
3/2 = 1.500000
请输入算式:bye
>>>
是想做个计算器么,网上搜一下源码,应该有吧
没想到eval函数还有这功能,学到了,看来还是我的方法麻烦