• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Finding Prime Numbers within a Given Range in Python

  • July 14, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial -:
  • Understanding the Problem
  • Developing the Algorithm
  • Writing the Python Code
  • Code Explanation
  • Dry Run
Finding Prime Numbers within a Given Range in Python
Finding Prime Numbers within a Given Range in Python

Understanding the Problem

Before diving into the code, it’s essential to have a clear understanding of what prime numbers are and the problem at hand. Prime numbers are integers greater than 1 that have no divisors other than 1 and themselves. Our goal is to write a program that can identify all the prime numbers within a given range specified by the user.



Developing the Algorithm

To find the prime numbers lying within a given range, we can simply perform following steps:

1. Loop over the given range.

2. Within loop, we pick each element and check whether its prime or not.

Writing the Python Code

Now, let’s implement the algorithm in Python. Below is the code snippet that accomplishes this task:

def find_primes(start, end):
    primes = []
    for num in range(start, end + 1):
        if is_prime(num):
            primes.append(num)

    return primes


def is_prime(number):
    if number < 2:
        return False

    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            return False

    return True


# Testing the function
start_range = int(input("Enter the starting range: "))
end_range = int(input("Enter the ending range: "))

prime_numbers = find_primes(start_range, end_range)

print("Prime numbers within the given range are:")
for prime in prime_numbers:
    print(prime, end=" ")

O/P

Enter the starting range: 1
Enter the ending range: 100
Prime numbers within the given range are:

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

Code Explanation

In this implementation, we define a function is_prime that takes a number as input and checks whether it is prime or not. Here’s how it works:

1. If the number is less than 2, it is not prime (since prime numbers are greater than or equal to 2), so we return False.
2. We iterate from 2 up to the square root of the given number (int(number**0.5) + 1), checking if the number is divisible by any of the values in that range.
3. If the number is divisible by any of the values in the range, we return False.
4. If none of the values in the range divide the number, we return True, indicating that the number is prime.
5. Finally, we test the function by taking user input for a number and checking whether it is prime or not. The program then prints the corresponding message based on the result.

This implementation is efficient for checking individual numbers, but if you need to find prime numbers within a range, using the Sieve of Eratosthenes algorithm (as explained here) would be more efficient.



Dry Run

Let’s perform a dry run of the code with an example:

1. Suppose the user enters a starting range of 10 and an ending range of 30.

2. The find_primes function is called with start_range = 10 and end_range = 30.

3. The function initializes an empty list called primes.

4. The for loop iterates over each number in the range from 10 to 30 (inclusive).

  • For the first iteration, num = 10.
    • The is_prime function is called with number = 10.
    • Since 10 is not less than 2, we proceed to the next step.
    • The for loop in the is_prime function starts from 2 and iterates up to the square root of 10 (4 in this case).
    • In the first iteration, i = 2. Since 10 % 2 is 0, we return False from the is_prime function.
    • The is_prime function call evaluates to False, so 10 is not considered prime and is not appended to the primes list.
  • The loop continues in a similar manner for the remaining numbers in the range.
  • For the number 11, the is_prime function returns True, so it is appended to the primes list.
  • The same happens for the numbers 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, and 30.

5. After checking all numbers in the range, the function returns the primes list, which contains [11, 13, 17, 19, 23, 29].

6. The prime numbers within the given range are printed to the console: 11, 13, 17, 19, 23, 29.

O/P:

Enter the starting range: 10
Enter the ending range: 30
Prime numbers within the given range are:
11 13 17 19 23 29





Tags: Algorithm to find prime numbers in PythonEfficient method to find prime numbers in PythonHow to find prime numbers between two numbers in PythonHow to identify prime numbers using PythonPrime number checker in PythonPrime number generator in PythonPrime numbers within a given range PythonPython code for prime numbers in a rangePython code to calculate prime numbers between two valuesPython code to determine prime numbers in a given rangePython code to print prime numbers within rangePython function to check prime numbers in a rangePython implementation for finding prime numbers in a specified rangePython program for prime numbers with range inputPython program to find all prime numbers within a rangePython program to find prime numbers in a rangePython program to list prime numbers within a rangeSimple prime number finder in PythonStep-by-step guide to finding prime numbers in PythonTutorial: Finding prime numbers with Python
  • Previous Prime Numbers within a Given Range using Sieve of Eratosthenes
  • Next Performing CRUD Operations on DynamoDB with AWS Lambda using Boto3 in Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.