我已经制作了一个代码来计算电路中的电阻。它考虑了系列之间的每个变化'并且'并行'然后给出部件数量,每个部件的电阻器数量和每个电阻器的电阻。
def resistance():
p = int(input('Enter number of parts. One "part" is a resistor or sequence of resistors that are in parallel while the rest are in series, or vice versa.'))
for x in range(1, p):
n = input('Enter number of resistors in part' + x)
for y in range(1, n):
w = input('Enter the resistance of resistor #' + y)
q.append(w)
t = str(input('In series or parallel? Enter S for series, P for parallel.'))
if t == 'S':
for z in range(1, len(q)):
s += q[z-1]
elif t == 'P':
for v in range(1, len(q)):
s += (1/q[z-1])
q = []
return s
问题是,无论何时我运行它都会接收到'然后会出现以下错误:
本地变量'在分配前引用
当我在第一个循环之前设置s = 0时,它只需要输入' p'然后返回0。
谁能告诉我哪里出错了?
编辑:上述问题已经解决,但现在又出现了问题。代码如下:def resistance():
s = 0
q = []
p = int(input('Enter number of parts. One "part" is a resistor or sequence of resistors that are in parallel while the rest are in series, or vice versa. '))
p += 1
for x in range(1, p):
n = int(input('Enter number of resistors in part ' + str(x) + ':'))
n += 1
for y in range(1, n):
w = input('Enter the resistance of resistor #' + str(y) + ', in ohms:')
q.append(w)
t = str(input('In series or parallel? Enter S for series, P for parallel. '))
if t == 'S':
for z in range(1, len(q)+1):
s += int(q[z-1])
elif t == 'P':
for v in range(1, len(q)+1):
s += int(1/int(q[z-1]))
q = []
return s
它是串联工作,但同时它说: - 虽然我在'系列中做了几乎相同的事情'部分,那里没有错误。将不胜感激。
答案 0 :(得分:0)
在您的代码中,您需要更改一些内容,首先初始化变量s=0
和列表q = []。使用输入时,它会尝试添加字符串'enter ...'和整数x,y
,如果您希望它添加两个整数,则将n
定义为
n = input('input number')+x
,结果是两个加的整数。此外,当您对串行或并行执行输入时,您将收到一条错误,指出S未定义或P未定义,您可以使用raw_input来解决此问题,并将S或P输入转换为字符串。这是代码:
def resistance():
s = 0
q = []
p = int(input('Enter number of parts. One "part" is a resistor or sequence of resistors that are in parallel while the rest are in series, or vice versa. '))
for x in range(1, p):
n = input('Enter number of resistors in part ')+x
for y in range(1, n):
w = float(input('Enter the resistance of resistor # '))+y
q.append(w)
t = raw_input('In series or parallel? Enter S for series, P for parallel. ')
if t == 'S':
for z in range(1, len(q)):
s += q[z-1]
elif t == 'P':
for v in range(1, len(q)):
s += (1/q[v-1])
q = []
return s
def test():
print resistance()
if __name__=='__main__':
test()