Count Prime Numbers in Range
Count how many prime numbers appear in a given inclusive range.
BeginnerTopic: Loop Programs
Python Count Prime Numbers in Range Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to count prime numbers in a range
start = int(input("Enter start of range: "))
end = int(input("Enter end of range: "))
count = 0
for num in range(start, end + 1):
if num < 2:
continue
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
count += 1
print(f"Number of primes between {start} and {end} is {count}")Output
Enter start of range: 1 Enter end of range: 10 Number of primes between 1 and 10 is 4
Understanding Count Prime Numbers in Range
We reuse the primality test logic but increment a counter instead of printing each prime.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.