Define a function that takes two integers (start, end) and classify the numbers between the range as prime and non-prime number and print the prime numbers
def is_prime(n):
if n < 1:
return False
for i in range(2, n 1):
if n % i == 0:
return False
return True
def print_primes(start, end):
for i in range(start, end):
if is_prime(i):
print(i)
a=int(input("Start value: ")
b=int(input("End value: ")
print_primes(a,b)
CodePudding user response:
def is_prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
def print_primes(start, end):
for i in range(start, end 1):
if is_prime(i):
print(i)
a=int(input("Start value:")
b=int(input("End value:")
print_primes(a,b)
CodePudding user response:
Some bugs which are fixed.
(1) you have not closed round parameter while taking input from the user a
and b
(2) is_prime()
. for loop run till n-1
not till the n
(3) stored answer in res for the readability.
Code:-
def is_prime(n):
if n < 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
def print_primes(start, end):
res=[]
for i in range(start, end):
if is_prime(i):
res.append(i)
return res
a=int(input("Start value: "))
b=int(input("End value: "))
print(print_primes(a,b))
Output:
Start value: 3
End value: 13
[3, 5, 7, 11]
As you can see start value is inclusive and end value is exclusive to make both inclusive just iterated to end 1
in print_primes
function
CodePudding user response:
def is_prime(n):
if n < 1:
return False
for i in range(2, n 1):
It should be:
def is_prime(n):
if n < 1:
return False
for i in range(2, n):
It should go till less than n, else n
will always be divisible by i
and return False
a=int(input("Start value:")) # make sure to close the parenthesis
b=int(input("End value:")) # make sure to close the parenthesis
CodePudding user response:
This takes into account the problem of float in range. Try it. :)
def is_prime(n):
if not n < 1:
for i in range(2, n):
if not n % i == 0:
return True
else:
return False
def print_primes(start, end):
res=[]
start=int(start)
end=int(end)
for i in range(start, end 1):
if is_prime(i):
res.append(i)
return res
#a=int(input("Start value: "))
#b=int(input("End value: "))
a=0.3
b=41
print_primes(a,b)
#[3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41]