-1
def prime(upper):
    while upper >=2:
        for num in range(2, upper + 1):
            prime = True
            for i in range(2, num):
                if (num % i == 0):
                    prime = False
            if prime:
                print(num, end=",")
                if num == upper:   #I think there is a problem here
                   break
prime(7)

How can I stop this function when it reachs 7 value PS: I want to execute this codes with while loop. BTW if you can make it this codes without for-loop please do it for me :) I appreciate you...

Alperen
  • 3,772
  • 3
  • 27
  • 49
Twister Joe
  • 111
  • 2
  • 11

1 Answers1

0

EDIT:

I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)

def is_prime(n):
    """"pre-condition: n is a nonnegative integer
    post-condition: return True if n is prime and False otherwise."""
    if n < 2: 
         return False;
    if n % 2 == 0:             
         return n == 2  # return False
    k = 3
    while k*k <= n:
         if n % k == 0:
             return False
         k += 2
    return True

You should use this function.

BEFORE EDIT:

I would use the is_prime function from here. You can use another way.

And, I would suggest this code for you:

def is_prime(Number):
    return 2 in [Number, 2**Number%Number]

def prime(upper):
    print([num for num in range(2, upper + 1) if is_prime(num)])

prime(7)

Output:

[2, 3, 5, 7]

But if you insist on using only while loop, you can modify your prime function as:

def prime(upper):
    num = 2
    while num <= upper:
        if is_prime(num):
            print(num, end = ",")
        num += 1

Then, output will be:

2,3,5,7,
Alperen
  • 3,772
  • 3
  • 27
  • 49
  • its kind of help me but can I ask that what is the purpose of this code **return 2 in [Number, 2**Number%Number]** – Twister Joe Dec 04 '17 at 18:38
  • It is just a function I found on the internet. I don't know its logic. There are other functions in the link given in the answer. – Alperen Dec 04 '17 at 18:43
  • If you can't find the link, click [here](https://stackoverflow.com/questions/15285534/isprime-function-for-python-language/32882220#32882220). I gues, this way is a little problematic, there are poor comments in the link. I chose it because it is short. You can use another `is_prime` function. – Alperen Dec 04 '17 at 18:46
  • @TwisterJoe I edited my answer. You can use the new `is_prime` function. – Alperen Dec 04 '17 at 18:50