3

I am learning Python currently. I wanted to get help to understand how the If and For function work when certain conditions don't get met. I am trying to define a function that will determine the number of prime numbers starting from 2 till the input number. For eg - count_primes(100) will give the output as 25 (total number of prime numbers between 0 and 100)

I wanted to increase the counter i by 1 only when the complete for loop for range (2,item) does not have any instances of n where the item % n (remainder of item divided by n) is equal to zero or item % n is not equal to zero for all n instances within the for n in range (2,item) loop.

Broader question: How do you write the code for cases where we might want to return a single variable based on the outcome of the entire for loop as in this case ?

My code is as follows -

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

Thanks in advance to all who chose to share their feedback and guidance.

--
Kind Regards,
Nilotpal

  • You could set a flag in your inner `if` loop and increment `i` based on the value of the flag. – athul.sure Apr 10 '20 at 13:09
  • 1
    This might also be helpful: https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops – athul.sure Apr 10 '20 at 13:12

2 Answers2

2

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 
Gabio
  • 9,126
  • 3
  • 12
  • 32
1

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
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8