-4

I successfully create a code to determine a prime number,is like this

def isprime(num):
  for x in range(2,num):
    if num%x == 0:
      return False
      break
    else:
      return True
dash = "-------------"
print(dash)
while 1:
 no = int(input("Enter number to determine: "))
 print(isprime(no))

Then, I decide to write a function so to let the output be all prime numbers in range(x,y). So I try,

def primein(minNum,maxNum):
  for num in range(minNum,maxNum):    
    for x in range(2,num):              
       if num % x == 0: #DefinitelyNotPrime
         return  True
       else:
         return False
    if True:
      print(num)
       
a = int(input("From: "))
b = int(input("To: "))
print(primein(a,b))

And I also try,

def primein(minNum,maxNum):
  for num in range(minNum,maxNum):
    fa = 0
    for x in range(2,num):      
       if num % x == 0: #DefinitelyNotPrime
         fa = 0
       else:
         fa = 1
    if fa == 1:
      print(num)
       
a = int(input("From: "))
b = int(input("To: "))
primein(a,b)

And it is also not working. Can someone help me I'm so confused now.

Mortis_666
  • 33
  • 1
  • 6
  • Can you tell - Does a python library solve your challenge https://stackoverflow.com/questions/13326673/is-there-a-python-library-to-list-primes/42440056 ? Are you looking for custom code ? – sam May 06 '21 at 06:58

2 Answers2

3

There are lots of approaches, but the one that is probably most instructive is to compose your functions! If you have a function that tells you if a number is prime, use it.

def is_prime(num):
    for n in range(2, int(math.sqrt(num))+1):
        if num % n == 0:
            return False
    return True

def find_primes_between(min_, max_):
    primes = []
    for candidate in range(min_, max_+1):
        if is_prime(candidate):
            primes.append(candidate)
    return primes

This is super inefficient, and indeed it's shockingly accurate to say that the whole study of computer science can be described as "quickly finding prime numbers," but it works and it teaches you how to use functions in actual applications.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
0

you return (True or False) from primein as soon as you determine the primeness (or not) of the first number in the range. Thus you never get to the printing (nor to testing a second number).

Do as every programmer does and reuse well-established code, i.e., call your function isprime in primein to determine primeness. Apart from making this work, you also have a chance to speed up tthe isprimefunction on its own with automatic benefits for primein

Hagen von Eitzen
  • 2,109
  • 21
  • 25