Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to generate a list of prime numbers in a range - Python Program

Example 1 :

def primes_in_range(start, end): """Return primes between start and end.""" primes = [] for num in range(start, end+1): if num > 1: for i in range(2, int(num**0.5)+1): if num % i == 0: break else: primes.append(num) return primes print(primes_in_range(10, 30))

Output

 
OUTPUT  :
[11, 13, 17, 19, 23, 29]

Example 2 : Advanced Program

import math def is_prime(num): """ Checks if a given number is prime. Args: num (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if num <= 1: return False # Numbers less than or equal to 1 are not prime for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False # If divisible by any number, it's not prime return True # If no divisors found, it's prime def generate_primes_in_range(start, end): """ Generates a list of prime numbers within a specified range (inclusive). Args: start (int): The lower bound of the range. end (int): The upper bound of the range. Returns: list: A list containing prime numbers within the given range. """ prime_numbers = [] for number in range(start, end + 1): if is_prime(number): prime_numbers.append(number) return prime_numbers # Example Usage and Output: lower_bound = 10 upper_bound = 50 primes = generate_primes_in_range(lower_bound, upper_bound) print(f"Prime numbers between {lower_bound} and {upper_bound}: {primes}")

Output

 
OUTPUT  :
Prime numbers between 10 and 50: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Explanation:

is_prime(num) function:

  • This helper function takes an integer numas input.
  • It first handles edge cases: numbers less than or equal to 1 are not prime, so it returns False.
  • It then iterates from 2 up to the square root of num(inclusive). This optimization is based on the fact that if a number num has a divisor greater than its square root, it must also have a divisor smaller than its square root.
  • If numis divisible by any number in this range, it is not prime, and the function returns False.
  • If the loop completes without finding any divisors, numis prime, and the function returns True.

 

generate_primes_in_range(start, end) function:

  • This function takes startand end integers defining the range.
  • It initializes an empty list called prime_numbers.
  • It iterates through each numberin the specified range (from start to end, inclusive).
  • For each number, it calls the is_prime()function to check if it's prime.
  • If is_prime()returns True, the number is appended to the prime_numbers
  • Finally, the function returns the prime_numbers