【问题标题】:fill empty array using loop in python在python中使用循环填充空数组
【发布时间】: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 我忘记了,我认为两者都可以,因为我没有被要求让答案浮动或不浮动

标签: python arrays list


【解决方案1】:

我已经清理了你的程序。我在开头添加了一条消息print('Type number number OPERATOR to perform operation. Type STOP to end program.'),以指导读者。另外,我取出了 for 循环(您有一个 for 循环和一个 while 循环,这是多余的。此外,当您从一个空列表开始时,您需要在添加到列表时使用 append,因此传入索引将抛出错误。

hasil = []
print('Type number number OPERATOR to perform operation. Type STOP to end program.')
while True:
    inp = input()
    if inp == 'STOP':
        break
    angk1, angk2, ope = inp.split(" ")
    angk1, angk2, ope = [int(angk1),int(angk2),str(ope)]
    if ope=='ADD':
        hasil.append(angk1+angk2)
    elif ope=='MUL':
        hasil.append(angk1*angk2)
    elif ope=='DIV':
        hasil.append(angk1/angk2)
    elif ope=='SUB':
        hasil.append(angk1-angk2)
for i in hasil:
    print(i)
print('Done')

输入:

1 2 ADD    
4 100 MUL    
5 2 DIV
100 10 SUB

输出:

3
400
2.5
90
Done

【讨论】:

    【解决方案2】:

    尝试像这样构建列表:

     if ope=='ADD':
            x = (angk1+angk2)
            hasil.append(x)
    

    并且您可能想要打印 L 的值,看起来它可能不是您想要的基于循环结构的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 2020-09-11
      • 2014-04-09
      • 1970-01-01
      相关资源
      最近更新 更多