【发布时间】:2018-09-27 23:36:53
【问题描述】:
我是 python 新手,我被要求使用 3 个输入 int、int、str 制作一个基本计算器。输入和输出应该是这样的:
输入
1 2 添加
4 100 MUL
5 2 格
100 10 次
输出
3
400
2
90
这就是我想要做的:
angk1, angk2, ope = input().split(" ")
angk1, angk2, ope = [int(angk1),int(angk2),str(ope)]
hasil = []
i = hasil
L = 0
while True:
for L in range(1, 500):
if ope=='ADD':
hasil[L] = (angk1+angk2)
elif ope=='MUL':
hasil[L] = (angk1*angk2)
elif ope=='DIV':
hasil[L] = (angk1/angk2)
elif ope=='SUB':
hasil[L] = (angk1-angk2)
L += 1
i.extend(hasil)
if input()=='STOP':
break
print i
print 'Done'
结果是:
'123 123 ADD'
Traceback (most recent call last):
File "test.py", line 9, in <module>
hasil[L] = (angk1+angk2)
IndexError: list assignment index out of range
谁能指出我的错误?任何帮助表示赞赏。
【问题讨论】:
-
在 Python 中,您不能通过分配给不存在的索引来扩大列表 - 您必须使用
.append()或.extend()方法。 -
我注意到您将
5 2 DIV设置为2。你希望它是2还是2.5? -
@JoePatten 我忘记了,我认为两者都可以,因为我没有被要求让答案浮动或不浮动