Here's a Python script that finds and prints all prime numbers between 2 and a user-specified upper limit:
def is_prime(n):
"""Helper function to check if a number is prime"""
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def find_primes_up_to_n(upper_limit):
"""Function to find all primes up to the upper limit"""
primes = []
for num in range(2, upper_limit + 1):
if is_prime(num):
primes.append(num)
return primes
# Get input from user
while True:
try:
upper_limit = int(input("Enter an upper limit (must be greater than 1): "))
if upper_limit <= 1:
print("Please enter a number greater than 1.")
continue
break
except ValueError:
print("Please enter a valid integer.")
# Find and print prime numbers
prime_numbers = find_primes_up_to_n(upper_limit)
# Print results
if prime_numbers:
print(f"\nPrime numbers between 2 and {upper_limit} are:")
print(prime_numbers)
print(f"Total count of prime numbers: {len(prime_numbers)}")
else:
print(f"\nNo prime numbers found between 2 and {upper_limit}")
This script:
-
Defines an is_prime(n) helper function that:
- Returns False if the number is less than 2
- Checks for divisibility up to the square root of n (optimization)
- Returns True if no divisors are found
-
Defines a find_primes_up_to_n(upper_limit) function that:
- Creates an empty list to store prime numbers
- Checks each number from 2 to the upper limit
- Adds prime numbers to the list
- Returns the list of primes
-
Has a main program that:
- Uses a while loop with error handling to get valid user input
- Ensures the input is greater than 1
- Calls the prime-finding function
- Prints the results in a formatted way
Example output:
Enter an upper limit (must be greater than 1): 20
Prime numbers between 2 and 20 are:
[2, 3, 5, 7, 11, 13, 17, 19]
Total count of prime numbers: 8
If you enter an invalid input:
Enter an upper limit (must be greater than 1): abc
Please enter a valid integer.
Enter an upper limit (must be greater than 1): 0
Please enter a number greater than 1.
Enter an upper limit (must be greater than 1):
The script is efficient for reasonable upper limits and includes error handling to ensure valid input. For very large numbers, you might want to consider more optimized algorithms like the Sieve of Eratosthenes, but this implementation is good for learning and general use.