即使使用while循环PYTHON,代码也不会停止

lb3vh1jj  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(168)

我试图让用户输入8次,然后输出数组。但是while循环似乎由于某种原因没有停止?下面是我的代码:

from numpy import*
t = array([int()]*200)

def premier(n):
    b = True
    for i in range(2,n//2):
        if n%i==0:
            b = False
    return(b)

def quadruplets(t):
    k=1
    while k < 8:
        
        for i in range(0,len(t),4):
            
            t[i] = int(input("Give t of I: "))
            if premier(t[i]) == False:
                t[i] = int(input("Don't make this harder than it already is: "))
            t[i+1]=t[i]+2
            t[i+2]=t[i]+6
            t[i+3]=t[i]+8
            print(t)
            k+=1
            print("your k is now: ",k)
        
quadruplets(t)
print("your final table is: ",t)
ecbunoof

ecbunoof1#

你使用了numpy模块,但实际上并没有使用它的任何特性,你只是使用列表解析创建了一个int数组。第二,你的while循环永远不会结束,因为你在for循环中递增了k的值,这意味着k总是小于8。你应该在for循环之后递增k。
以下是修复代码的方法:

from numpy import array

def premier(n):
    b = True
    for i in range(2,n//2):
        if n%i==0:
            b = False
    return(b)

def quadruplets(t):
    k = 0
    while k < 8:
        for i in range(0,len(t),4):
            t[i] = int(input("Give t of I: "))
            if premier(t[i]) == False:
                t[i] = int(input("Don't make this harder than it already is: "))
            t[i+1]=t[i]+2
            t[i+2]=t[i]+6
            t[i+3]=t[i]+8
        k += 1
        print("your k is now: ",k)
        
t = array([int()]*200)
quadruplets(t)
print("your final table is: ",t)

但是,我建议您通过删除while循环并使用for循环来进一步简化代码,因为您已经知道要迭代8次:

from numpy import array

def premier(n):
    b = True
    for i in range(2,n//2):
        if n%i==0:
            b = False
    return(b)

def quadruplets(t):
    for k in range(8):
        for i in range(0,len(t),4):
            t[i] = int(input("Give t of I: "))
            if premier(t[i]) == False:
                t[i] = int(input("Don't make this harder than it already is: "))
            t[i+1]=t[i]+2
            t[i+2]=t[i]+6
            t[i+3]=t[i]+8
        print("your k is now: ",k+1)
        
t = array([int()]*200)
quadruplets(t)
print("your final table is: ",t)

最后,您应该考虑为变量提供更具描述性的名称,以使代码更易于阅读和理解。

相关问题