Tuple of prime numbers up to 50 in Python


This Python code defines a function is_prime(n) to check if a number n is prime, and then it creates a tuple called primes containing all prime numbers from 2 to 50. Here's how the code works:

  • def is_prime(n): This line defines a function named is_prime that takes an integer n as its argument.
    • if n <= 1:: This line checks if the input number is less than or equal to 1, in which case it returns False because prime numbers are greater than 1.
    • for i in range(2, int(n**0.5) + 1):: This line sets up a loop that iterates through numbers from 2 to the square root of n (rounded up to the nearest integer) plus 1. This loop is used to check if n is divisible by any number in that range.
      • if n % i == 0:: For each i in the loop, it checks if n is divisible by i (i.e., if the remainder of the division is 0). If n is divisible by any number in the range, it means n is not prime, and it returns False.
    • If the loop completes without finding a divisor, the function returns True, indicating that the input number is prime.
  • primes = tuple(x for x in range(2, 51) if is_prime(x)): This line of code initializes a variable named primes and assigns it a tuple created using a generator expression.
    • for x in range(2, 51): This part of the code sets up a loop that iterates through numbers from 2 to 50.
    • if is_prime(x): For each number x, it checks if it is prime by calling the is_prime function. If x is prime, it includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated prime numbers into a tuple.
  • print(primes): This line of code prints the primes tuple (which contains all prime numbers from 2 to 50) to the console.

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
 
primes = tuple(x for x in range(2, 51) if is_prime(x))
print(primes)

Output

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

Example Programs