Python Find the Prime Numbers from 1 to 100
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
)
]
(
primes
)
Code analysis:
is_prime(n)The function is used to determine whether a numbernis prime. First check whethernCheck whether it is less than or equal to 1; if so, returnFalse, because a prime number must be greater than 1.- Then use a
forThe loop iterates from 2 tonthe square root ofint(n ** 0.5) + 1), checkingnwhether it is divisible by these numbers. If it is divisible, thennis not a prime number, returnFalse。 - If after the loop no number that divides
nis found, thennis a prime number, returnTrue。 - 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 inprimeslist. - Finally, print the
primeslist, 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]
Python3 Examples