Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Prime Numbers from 1 to 100

Python Find the Prime Numbers from 1 to 100

Document Object Reference Manual Python3 Examples

To find all prime numbers between 1 and 100, we can write a Python program. A prime number is a natural number greater than 1 that is divisible only by 1 and itself. We can do this by iterating over every number from 1 to 100 and checking whether it is prime.

Example

def

is_prime

(

n

)

:

   

if

n

<=

1

:

       

return

False

   

for

i

in

range

(

2

,

int

(

n **

0.5

)

1

)

:

       

if

n % i

==

0

:

           

return

False

   

return

True

primes

=

[

x

for

x

in

range

(

1

,

101

)

if

is_prime

(

x

)

]

print

(

primes

)

Code analysis:

  1. is_prime(n) The function is used to determine whether a number n is prime. First check whether n Check whether it is less than or equal to 1; if so, return False, because a prime number must be greater than 1.
  2. Then use a for The loop iterates from 2 to n the square root ofint(n ** 0.5) + 1), checking n whether it is divisible by these numbers. If it is divisible, then n is not a prime number, return False。
  3. If after the loop no number that divides n is found, then n is a prime number, return True。
  4. Use a list comprehension [x for x in range(1, 101) if is_prime(x)] Generate all prime numbers between 1 and 100 and store the result in primes list.
  5. Finally, print the primes list, outputting all prime numbers between 1 and 100.

Output result:


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Document Object Reference Manual Python3 Examples