Python: Prime Numbers in Range
Python: Prime Numbers in a Range
Our task here is simple as the title, we will have a range and will test each number to see if it is a prime then we will add it to a list, once we finish we will print out the list.
To complete this task we will use one of our function we create last time (Read: is prime post).
So, here we will ask the user to input two numbers num1 and num2 the we will pass all the numbers in the range to is_prime() and store the result in a list.
The Code:
#Function to get all Prime numbers in a range.
#Ask the user to enter two numbers
print ‘Get all Prime numbers in a range\n’
num1=int(input(“Enter the first number in the range: “))
num2=int(input(“Enter the last number in the range: “))
#create the list
prime_list=[]
def get_all_prime(num1,num2):
for x in range (num1,num2):
if is_prime(x) ==’Prime’:
prime_list.append(x)
return prime_list
#Call the function and print the list
get_all_prime(num1,num2)
print prime_list
print len(prime_list)