Python Find Prime Numbers from 1 to 100

Document 对象参考手册Python3 Examples

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

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 numbernis a prime number. First checknwhether it is less than or equal to 1. If so, returnFalse, because a prime number must be greater than 1.
  2. Then use aforloop to iterate from 2 tonthe square root of (int(n ** 0.5) + 1), checknwhether it can be divided by these numbers. If it can be divided, thennit is not a prime number, returnFalse。
  3. If after the loop ends no number that dividesnis found, thennit is a prime number, returnTrue。
  4. Use a list comprehension[x for x in range(1, 101) if is_prime(x)]to generate all prime numbers between 1 and 100, and store the result inprimesthe list.
  5. Finally, printprimesthe 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 对象参考手册Python3 Examples

Other Extensions