2017-10-28 78 views
-1

我目前正試圖編寫一個程序,收集所有電阻,計算,然後獲取電壓,然後計算電流。以下是我迄今爲止:電阻計算器說索引超出範圍

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 

回答

0

你只是讀1個電阻值,如果你return環路。

移動return退出循環,或刪除它,因爲Python並不需要明確的回報,你沒有返回值:

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