Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading