Skip to Main Content
Blog

Print all Prime Numbers in Python

Print all Prime Numbers in Python

Enter lower bound: 1
Enter upper bound: 49
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
import math


# Checks if a number is a Prime number or not.
def is_prime(num: int) -> bool:
    """
    Checks if a number is prime.

    Args:
    num (int): The number to check.

    Returns:
    bool: True if the number is prime, False otherwise.
    """
    if num <= 1:  # Numbers less than or equal to 1 are not prime
        return False
    if num <= 3:  # 2 and 3 are prime
        return True
    if num % 2 == 0 or num % 3 == 0:  # If divisible by 2 or 3, not prime
        return False

    # Only need to check up to the square root of num
    for d in range(5, int(math.sqrt(num)) + 1, 2):
        if num % d == 0:  # If divisible by any number, not prime
            return False

    return True  # If not divisible by any number, prime


def main():
    # Get the lower and upper limits from the user
    lower_limit = int(input("Enter lower limit: "))
    upper_limit = int(input("Enter upper limit: "))

    # Print all prime numbers in the given range
    for i in range(lower_limit, upper_limit + 1):
        if is_prime(i):
            print(i, end=", ")
    print()  # Newline for readability


if __name__ == "__main__":
    main()