3 Replies - 369 Views - Last Post: 01 October 2011 - 11:07 AM Rate Topic: -----

#1 cupcake18  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 01-October 11

Trouble using for loop.

Posted 01 October 2011 - 09:35 AM

def isprime(num):
    num*=1.0
    for i in range(2,int(num**0.5)+1):
        if num/i==int(num/i):
            return False
    return True
	
for a in range(2,100):
		
    	if isprime(a):
		
		for count in range(1,a):
				
			print "PRIME NO.:",count,"=",a
				
			break



Why is "count" not getting incremented?
Thanks in advance! :)

Is This A Good Question/Topic? 0
  • +

Replies To: Trouble using for loop.

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2153
  • View blog
  • Posts: 3,312
  • Joined: 21-June 11

Re: Trouble using for loop.

Posted 01 October 2011 - 10:31 AM

You have a for loop which counts from 1 to a, however you use break to break out of the loop after the first iteration. So each time you go into the loop, count is set to 1 and then you exit the loop before count will be anything else. So that's why count is not incremented.

If you remove the break, count will get incremented, but probably not in the way you want (it's hard to say for sure of course, because you did not specify what you want, but I can't see a reason why you'd want the behavior you get when removing break).

To get the behavior that I suspect you want (though again it's hard to say when you never actually say what you want), you should get rid of the inner for loop and just manually keep track of a counter, which you increment each time you find a prime number.
Was This Post Helpful? 1
  • +
  • -

#3 cupcake18  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 01-October 11

Re: Trouble using for loop.

Posted 01 October 2011 - 10:45 AM

View Postsepp2k, on 01 October 2011 - 10:31 AM, said:

(it's hard to say for sure of course, because you did not specify what you want, but I can't see a reason why you'd want the behavior you get when removing break).


Sorry! My bad. I want the output to print primes till a specific number. Like, if I want to know the 146th number or something I want it in the output. Not sure if I'm being clear or not. :S
Something like:
Prime No.: 6=13
Was This Post Helpful? 0
  • +
  • -

#4 cupcake18  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 01-October 11

Re: Trouble using for loop.

Posted 01 October 2011 - 11:07 AM

sepp2k,
Removed the inner for loop like you said and made little changes to the code. It's working! Thanks! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1