'I want to print the list of prime numbers in a given range, what is wrong with my code?

I am trying to print the list of prime numbers in a given range. I know we can directly use print statement in the for loop to print each prime number however, I want to print the entire list of prime numbers. What is wrong with my code?

def prime():
    upper_bound = int(input())

    while True:
        lower_bound = int(input())
        if lower_bound <= 2:
            print("Please enter number greater than 2")
        else:
            break
    
    prime_num = [2]
    
    i = lower_bound
   
    while i <= upper_bound+1:
        for k in range(2,i):
            if (i%k) == 0:
                i = i + 1
                break
                
        else:
            prime_num.append(i)
            i = i + 1
    
   
    print(prime_num)


Solution 1:[1]

You need to call the prime() function, then it'll print the array out.

Otherwise, you could loop through the array and add every character to a string so that you don't get the array formatting.

So:

Result = "";
for x in range(0, len(prime_num)):
    Result += str(prime_num[x]) + " ";
print(Result);

Solution 2:[2]

I think it working properly I run it and give the output. Just call the prime() function.

def prime():
upper_bound = int(input("please enter upper bound"))
while True:
    lower_bound = int(input("please enter lower bound"))
    if lower_bound <=2:
        print("Please enter number greater than 2")
    else:
        break
prime_num = [2]
i = lower_bound
while i <= upper_bound + 1:
    for k in range(2, i):
        if (i % k) == 0:
            i = i + 1
            break
    else:
        prime_num.append(i)
        i = i + 1


prime()

and here is the output

please enter upper bound20

please enter lower bound3

[2, 3, 5, 7, 11, 13, 17, 19]

Solution 3:[3]

The fastest method:

import sympy
    
print(list(sympy.primerange(0, 1_000_000_000)))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BBonless
Solution 2
Solution 3 gerald