Hi everyone I am learning python, I came across a sample program which checks whether the given number is prime number or is not a prime number using for loop and range() function. I can't understand that program, can someone please help me understand it? Here is the program and the output. So initially what will the variable 'n' hold?

for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, ’equals’, x, ’*’, n/x
... break
... else:
... # loop fell through without finding a factor
... print n, ’is a prime number’
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

Edited by Varunkrishna

3 Years
Discussion Span
Last Post by lucpet

The program is using nested for loops - http://www.tutorialspoint.com/python/python_nested_loops.htm

It is also usin modulo which is "%" this works out the remainder therefore if:

n / x = 0

the if statement will be true.

Therefore it will run:

print n, ’equals’, x, ’*’, n/x

Eitherwise if n / x is not = 0, it will run the following line of code:

print n, ’is a prime number’

so what value will the variable n takes? Initially after applying the range(2,10), n will hold (2-9). then what will the variable x holds? That first two for loops are confusing me...


range(2,10) generates a list, [2,3,4,5,6,7,8,9]
for n in range(2,10) assigns n to the next element in the result from range(2,10) and then executes the code, repeat
range(2,n) takes n and generates [2,3,4....,n-1]

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.