Home > Enterprise >  Why does using for loop for finding prime number runs only runs once?
Why does using for loop for finding prime number runs only runs once?

Time:08-30

I want to find the prime numbers up to the given number but my loop only runs once and my output is only 2 and 3, where did I went wrong?

def primer_check(n):
    prime_state = True
    for i in range(2,n 1):
        if i == 2:
            print(2)
            continue
        for j in range(2,i):
            if i % j == 0:
                prime_state = False
                break
        if prime_state: print(i)

n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)

CodePudding user response:

you have to set prime_state to True everytime when you start a new loop.here is the code.you are almost correct .Hope it helps :)

def primer_check(n):
    for i in range(2,n 1):
        prime_state = True
        if i == 2:
            print(2)
            continue
        for j in range(2,i):
            if i % j == 0:
                prime_state = False
                break
        if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)
  • Related