Is there any way to fix my python code being stuck?

Question:

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…..

Asked By: Khalboy

||

Answers:

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")
Answered By: Ohad Sharet
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.