阻力指数超出范围

2024-05-29 05:18:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序,收集所有电阻,计算,然后得到电压,然后计算电流。到目前为止,我掌握的情况如下:

resistors = [0]


def ObtainResistors(resistors):
    for i in range(1, 8):
            value = int(input('please enter resistor %d:' % i))
            resistors.append(value)
            return


def TotalResistance(resistors):
    rt1 = ((resistors[2] * resistors[3]) / (resistors[2] + resistors[3]))
    print(rt1, 'ohms')
    rt2 = (rt1 + resistors[4])
    print(rt2, 'ohms')
    rt3 = ((rt2 * resistors[5]) / (rt2 + resistors[5]))
    print(rt3, 'ohms')
    rt4 = (rt3 + resistors[7])
    print(rt4, 'ohms')
    rt5 = ((rt4 * resistors[6]) / (rt4 + resistors[6]))
    print(rt5, 'ohms')
    rt6 = (rt5 + resistors[1])
    print(rt6, 'ohms')
    rt = (rt1 + rt2 + rt3 + rt4 + rt5 + rt6)
    print(rt,  'ohms')
    return


ObtainResistors(resistors)
print(resistors)
TotalResistance(resistors)
print(resistors)

这是我跑步时得到的

please enter resistor 1:1
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/Introduction_to_Python/RESISTOR COURSEWORK.py", line 31, in <module>
    TotalResistance(resistors)
  File "C:/Users/User/PycharmProjects/Introduction_to_Python/RESISTOR COURSEWORK.py", line 12, in TotalResistance
    rt1 = ((resistors[2] * resistors[3]) / (resistors[2] + resistors[3]))
IndexError: list index out of range
[0, 1]

Process finished with exit code 1

Tags: invaluedefrangeprintrt3resistorsrt4
1条回答
网友
1楼 · 发布于 2024-05-29 05:18:21

如果在循环中return,则只读取1个电阻值。你知道吗

return移出循环,或者将其删除,因为Python不需要显式返回,而且您也不会返回值:

def ObtainResistors(resistors):
    for i in range(1, 8):
        value = int(input('please enter resistor %d:' % i))
        resistors.append(value)
    # return

相关问题 更多 >

    热门问题