Generate a set of prime numbers from 1 to 50


This Python code defines a function is_prime to check whether a given number is prime or not. Then, it uses a set comprehension to create a set called prime_numbers containing all prime numbers from 1 to 50. Here's a step-by-step explanation of the code:

  • def is_prime(n): This line defines a function named is_prime that takes an integer n as an argument. It will return True if n is a prime number and False otherwise.
  • if n <= 1:: This is the first condition. If n is less than or equal to 1, it's not a prime number. Prime numbers are greater than 1, so the function returns False in this case.
  • for i in range(2, int(n**0.5) + 1):: This loop iterates from 2 to the square root of n (rounded up to the nearest integer) plus 1. This is an optimization to reduce the number of divisors to check. Prime numbers have no divisors other than 1 and themselves, and we only need to check up to the square root of n.
  • if n % i == 0:: This condition checks if n is divisible by i. If it is, then n is not a prime number, and the function returns False.
  • return True: If the function doesn't return False in the previous conditions, it means that n is not divisible by any number in the given range, and it's a prime number. In this case, the function returns True.
  • prime_numbers = {x for x in range(1, 51) if is_prime(x)}: This line creates a set called prime_numbers using a set comprehension. It iterates over numbers from 1 to 50 and includes them in the set if the is_prime function returns True for that number. This set comprehension collects all prime numbers from 1 to 50.
  • print(prime_numbers): This line prints the prime_numbers set to the console, displaying all prime numbers between 1 and 50.

Source Code

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
 
prime_numbers = {x for x in range(1, 51) if is_prime(x)}
print(prime_numbers)

Output

{2, 3, 5, 37, 7, 41, 11, 43, 13, 47, 17, 19, 23, 29, 31}

Example Programs