Nilotpal Choudhury
Nilotpal Choudhury

Reputation: 135

Understanding the outcome a `FOR` loop with a nested `IF` statement

I have this code that should determine the number of primes between 2 and the input num:

def count_primes(num):
    i = 0

    for item in range(2, num):           
        for n in range(2, item):
            if item % n == 0:
                break
                
        i += 1
            
    return i

This doesn't work because i += 1 happens every time through the outer loop. I'm confused about how to combine if and for to make the logic work the way I want.

How can I make i += 1 only happen when the complete inner loop (for n in range(2, item):) runs without finding any instances where item % n == 0?

Upvotes: 4

Views: 72

Answers (2)

Gabio
Gabio

Reputation: 9494

You can use else with your for loop. The code block under else will be executed only when the for loop is exhausted, i.e - finished without breaking out.

for i in range(10):
# logic for each iteration
else:
# the code here will be executed  only if the loop finished 10 successful iterations 

Upvotes: 2

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

Do this :

def count_primes(num):
    i = 0
    for item in range(num):
        if item <= 1:
            continue
        for n in range(2, item):
            if item % n == 0:
                break
        else:
            i += 1
    return i

Upvotes: 1

Related Questions