while loop blues

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

while loop blues

Postby Nihilarian420 » Thu May 30, 2013 1:52 am

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 primeness
p = 0 ##number of primes found
a = 0 ##anti prime - experimenting to avoid else statements
x = 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

print 'you suck meatballs, plus ', p, ' primes has been reached'

Thanks a billion in advance,
Posts: 2
Joined: Wed May 29, 2013 1:08 pm

Re: while loop blues

Postby Mekire » Thu May 30, 2013 6:25 am

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 = 0
while 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

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.

New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Posts: 1711
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Re: while loop blues

Postby Nihilarian420 » Thu May 30, 2013 8:41 am

Ahhh true!

Thanks man very helpful.
Posts: 2
Joined: Wed May 29, 2013 1:08 pm

Return to General Coding Help

Who is online

Users browsing this forum: Alexa [Bot], Bing [Bot] and 9 guests