嵌套while循环不能在python中正确循环

时间:2015-04-20 19:53:56

标签: python loops while-loop

我是新手,我对我的python代码有疑问。它没有像我认为的那样执行。 弄乱的部分是嵌套的:

import math
mu=4*math.pi*10**(-7)  ##mu naught
I=
float(input('Enter a value for the current measured in Amperes: '))
R=abs(float(input('Enter a value for the radius 
of the circle measured in meters: '))) ##radius
step=R/200  ##Step size for integration
B=[] ##array for B(r)
J=[]
Plot=[B,J]

k = 1 ##step counter for Circumfrence
j = 1 ##step counter for Radius
b_temp = 0 ##place holder to sum b(step*k)

D_Vector = [R*math.cos(k*math.pi/100),R*math.sin(k*math.pi/100)]
R_Vector = [R-j*step,0]

while(j*step<=R):
    while(k*step<=2*math.pi*R):
        r=(math.sqrt((R_Vector[0]-D_Vector[0])**2 + 
        (R_Vector[1]-D_Vector[1])**2))
        b_temp = b_temp + (mu/(4*math.pi))*I*step*step/(r**2)
        k=k+1
        D_Vector = [R*math.cos(k*math.pi/100),R*math.sin(k*math.pi/100)]
        R_Vector = [R-j*step,0]
        print(round(r,3), j)
    B.append(round(b_temp,8))
    print('New j value!')
    b_temp=0
    J.append(round(step*j,3))

    j=j+1

它应该逐步降低半径(第一个while循环),然后围绕圆圈循环,总结每个线束的磁场贡献。出于某种原因,它不会像外部循环那样循环遍历内部循环的内部循环,而且老实说我不确定为什么。新的j值行是让我看看它是否正常循环,这是我的输出:

...
13.657 1
13.884 1
14.107 1
14.327 1
14.543 1
14.756 1
14.965 1
15.17 1
15.372 1
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
New j value!
...

每个浮点(半径值)末尾的1是j值,循环周围的每个圆圈都保持为1 ......

1 个答案:

答案 0 :(得分:1)

您正在增加k,但从未将其重置为1。所以k * step变得越来越大,直到内循环的条件变为假。在这一点上很明显,它不再被执行。

请注意,当您只是在整数范围内迭代时,应该避免while循环。只需使用for j in range(a, b)即可。这样可以避免代码中出现的错误。

如果我没弄错,你可以用以下代码替换循环:

area = 2*math.pi*R

for j in range(1, R//step + 1):
    # j*step <= R holds
    for k in range(1, area // step + 1):
        # k * step <= area holds here

其中a // bab的商。