Home > Software engineering >  Is there any way to fix my python code being stuck?
Is there any way to fix my python code being stuck?

Time:08-07

primeNum = []

def isPrime(y):
    i = 2
    while(i < number):  
        if number % i == 0: 
           return False
    i = i   1
    return True

def printNum(x):
    k = 2  
    while k <= x:
        if isPrime(k):
            primeNum.append(k)
    k = k   1        
     
printNum(number)

numOfPrime = len(primeNum)
sum = 0

j= 0
while j < numOfPrime:
    sum  = primeNum[j]
j = j   1  

print(sum)

When I run the code it just gets stuck on the input. I have tried everything but it doesn't give me an error unless I press CTRL C then it will tell me Traceback.....

CodePudding user response:

the line k = k 1 in the function printNum was out of the while loop , making it an infinite loop,same goes for i = i 1 in isPrime and j = j 1 in the last loop, so i fixed it for you

additionally, the function isPrime had some bugs it referred to number instead of y in a few places so I fixed that too

this should do the trick:

primeNum = []

number=10
def isPrime(y):
    i = 2
    while (i < y):
        if y % i == 0:
            return False
        i = i   1
    return True


def printNum(x):
    k = 2
    while k <= x:
        if isPrime(k):
            primeNum.append(k)
        k = k   1


printNum(number)

numOfPrime = len(primeNum)
sum = 0

j = 0
while j < numOfPrime:
    sum  = primeNum[j]
    j = j   1

print(sum)
print("end")
  • Related