## while loop blues

This is the place for queries that don't fit in any of the other categories.

### while loop blues

Hi,
I've recently started trying to learn to code however i'm having a hard time when trying to build my own code. Any help would be greatly appreciated

The purpose of this code is to identify a prime number... i.e. the 20th prime number is 71. My problem is that my while loop does not end when p is no longer < 10.

Code: Select all
`## n = number being evaluated for primenessp = 0 ##number of primes founda = 0 ##anti prime - experimenting to avoid else statementsx = 3 ##is bumper to keep n increasing##r is range for n calculations to determine divisibility.while p < 10: #change this number for prime number required.        for n in range(2, 50): ##replace 50 with x to make an infinite loop        x = x + 1        print '\n\nEvaluating', n, 'for primeness:'        c = 0        for r in range(2, n): ##checking primeness            v = n%r            print n, '%', r, '=', v                        if v == 0:                print n, ' is not a prime'                a = a + 1                print 'number of primes should be', n - a                p = n - a                breakprint 'you suck meatballs, plus ', p, ' primes has been reached'`

Nihilarian420

Posts: 2
Joined: Wed May 29, 2013 1:08 pm

### Re: while loop blues

You are breaking out of one for loop but you are still in the other for loop. The while loop doesn't automatically end as soon as p > 10. It checks this condition once every time through the whole while loop.

Code: Select all
`p = 0while p < 10:    for n in range(2, 50):        #Everytime you get to the break you end up back here        #until this loop finishes.        for r in range(2, n):            p += 1            breakprint(p)`
The above, as you can see, won't end when p exceeds 10.

There is no multi loop break in python. You can accomplish similar things by using flags but at this point I would actually suggest you completely re-examine your approach. Another interesting thing to note is you will only need to check for divisors up to the square root of your number. If you think about it you will realize why.

-Mek
• Use code tags when posting code.
• Include any errors with your post (in code tags).
• Make examples the minimum length to demonstrate your issue.

Mekire

Posts: 1583
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Ahhh true!