简体   繁体   中英

Python - Prime Number exercise

Note, this is not my homework assignment! I'm just trying to understand Python (and math, sadly) at the same time. I know the ultimate goal of this program is to get a list of prime numbers in the range 1 to 20, however, once it gets to the "for x in range..." line, I'm getting lost and the tutorial doesn't explain it in detail.

Could you please explain in plain English step by step and clarify specifically

a) what is x in the line for x in range (2,n)

b) in the line for x in range (2,n), what is n ? Is it the same "n" at the bottom?

c) what is this n, x, n // x saying exactly. Please clarify the //

thanks if you can help

def isprime(n):
    if n == 1:
        print("1 is special")
        return False
    for x in range(2, n):
        if n % x == 0:
            print("{} equals {} x {}".format(n, x, n // x))
            return False
    else:
        print(n, "is a prime number")
        return True

for n in range(1, 20):
    isprime(n)

a)

for x in range (2,n)

is the same like

for (x = 2; x < n; x++)

in some other language: a loop where x gets integer values between 2 and n-1 included.

b)

for x in range (2,n): 

this n comes from the first def isprime(n) and is whatever this function is later called with. In this case it is always the same n from the bottom.

c)

print("{} equals {} x {}".format(n, x, n // x))

this writes the following text: A equals B x C where A is n , B is x and C is n/x rounded to the nearest smaller integer. It is so called integer division (eg 9 // 2 = 4 )

a) Try this at the prompt:

help(range)

It will tell you that range(a,b) returns a list atarting as a, ending at b-1, so

range(2,10)

is

[2, 3, 4, 5, 6, 7, 8, 9]

Play at the prompt, type range(2,2) , range(2,-1) , range(2,3) and see what comes out. You'll see that n==1 isn't the only special case.

Now, something like for x in y iterates over the elements of y, which in your case would be a list. You can also verify this at the prompt:

for x in range(2,10) :
    print x

b) the block starting with def isprime(n) is a function, with argument n. You can call it for any n: isprime(100) . At the bottom of the code, you are iterating over range(1,20) (if in doubt type it into the prompt) and calling isprime for each value, ie 1,2,3,4,...,19.

Note that in this example, there isn't a need to create and return a list with range , you can use xrange , which is a generator. Type help(xrange) in the prompt...

a) x takes on the values from 2 to n-1 (since range excludes the upper bound)

b) No, it's the same n as in the method definition (ie the method argument)

c) Integer division

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM