0

I want to run a function (def) 100 times using while (with numbers from 0 - 1000000)

But the while doesn't break the loop when needed. How can I fix it?

count = 2  #I start from 2 on purpose
limit = 101

def is_prime(i):
    global count
    count+=1
    #there is more to the function is_prime but it isn't relevant 
    #i made a function with input to show a example

while (count < limit):
    for i in range(1000000):
        is_prime(i)
        print ("count = ", count)

I expect it to stop when it gets to count = 100

2
  • Now that you changed it, the issue cannot be reproduced. The code does not hang. Commented Aug 30, 2019 at 12:17
  • The inner for loop does not care about the exit strategy of the outer while loop, thus it will go on until it reaches the end ( range(1000000) in your case ) and then then while loop exits. Commented Aug 30, 2019 at 12:18

1 Answer 1

0

Try this one - in order to interact with the global variable from the inside of subroutine - you need to indicate it's global. Otherwise it's just local function variable with the same name, as the existing global variable

count = 2  #I start from 2 on purpose
limit = 101

def is_prime(i):
    global count
    count+=1
    #there is more to the function is_prime but it isn't relevant 
    #i made a function with input to show a example

while (count < limit):
    for i in range(1000000):
        is_prime(i)
        print ("count = ", count)
print(count)
Sign up to request clarification or add additional context in comments.

4 Comments

sorry, my mistake I already tried it and I forgot to put it in the code. unfortunately, it didn't work...
but it limits while loop, why it doesn't work from your perspective ? I.e. what would you like to have differently in terms of outcome ?
it doesn't work from my perspective because the loop didn't "break" (stop) after the while conditional is False. I don't get any errors it just continue forever
It did, it just first executes inner for - and once for is done, re-evaluates condition in while

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.