Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Prime number code
#1
The assignment is to write a function that returns the number of prime numbers that exist up to and including
a given number. The solution is below but I'm having trouble interpreting it. The part I don't understand
is the 'for y in range(3,x,2)' loop part. In the first cycle of the loop, x = 3 so I see it as 'range(3,3,2) but this doesn't make sense because the middle number represents up to but not including. So a range of 3-2 doesn't make sense. Also why is 'else:' not lined up with 'if'? Can someone please help me understand how a range(3,3,2) works?
def count_primes2(num):
    primes = [2]
    x = 3
    if num < 2:
        return 0
    while x <= num:
        for y in primes:  # use the primes list!
            if x%y == 0:
                x += 2
                break
        else:
            primes.append(x)
            x += 2
    print(primes)
    return len(primes)
Reply
#2
A little problem is I don't see "range(3,x,2)" in your code. But that doesn't matter. When an iterator returns no data, the loop does not execute. In that case the for functions like an if statement.
You can easily test those things on the python command line.
>>> for i in range(3, 3, 2):
...     print(i)
... 
The result: it shows nothing because the loop is not executed.
Now the else. It is little known the for statement also may have an else clause. Please read The for statement. The else part is executed when the items are exhausted (which is immediately when the sequence is empty or an iterator raises a StopIteration exception). When a break is executed, the loop ends immediately and the else is also not executed.
You can alse test this easily on the python command line.
>>> for i in range(3, 3, 2):
...     print(i)
... else:
...     print('End')
... 
End
Reply
#3
The for statement is in your otherwise duplicate post.
Please don't duplicate posts
Please don't duplicate posts

One point in that code is that you go to the actual number -1. You can stop at half the limit as no number is divisible by a number greater than half its value
Reply
#4
Thank you for your help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to find the next prime number FirstBornAlbratross 8 4,279 Aug-14-2023, 01:16 PM
Last Post: deanhystad
  calculate the 10001st prime number topologh 7 6,204 Oct-05-2020, 07:41 PM
Last Post: deanhystad
  Trouble interpreting prime number code ryfoa6 1 2,250 Mar-20-2020, 03:47 PM
Last Post: stullis
  Asking for help in my code for a "Guess the number" game. Domz 5 3,796 Aug-14-2019, 12:35 PM
Last Post: perfringo
  Prime number Python homework mkrisz98 11 5,589 May-10-2019, 05:23 PM
Last Post: mkrisz98
  how to find a next prime number? iamyourfather 2 6,507 Oct-01-2017, 04:21 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020