-1

I'm trying to make a program which will output all prime numbers in a random numerical segment [a,b]. However I also need this program to use the inner for loop as well as for-else construction. I know that there are other great solutions out there to this problem, but I try tackling the issue using ONLY above-mentioned structures. The problem is that it doesn't even output prime numbers, but all numbers in the segment.

Input: a, b (where a,b belong to the set of integers)

Output: prime numbers in the segment: x1,x2,...,xN

Here's my solution:

# prime nums
x = int(input())
y = int(input())
res = 'prime numbers: '
for i in range (x,y,1):
    for j in range (i-1,0,-1):
        if (i%j == 0): 
            pass
    else:
        res=res+str(i)
print(res)

Thanks in advance!

JoshJohnson
  • 181
  • 3
  • 18
  • 2
    Because the `else` clause of the `for` will always execute because the `for` doesn't have a `break` statement... Read about this construct [in the docs](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops). Basically change the `pass` to `break`. Oh and you also need to change the `range`... Every number is divisible by `1`... A simpler way is just `range(2, i)` – Tomerikoo Sep 30 '20 at 11:09
  • Does this answer your question? [Print series of prime numbers in python](https://stackoverflow.com/questions/11619942/print-series-of-prime-numbers-in-python) – solid.py Sep 30 '20 at 11:38

2 Answers2

2

I don't understand why you want a string of numbers to be printed along. You can store it in a list by appending. But anyways to answer your question:

Method 1:

x = int(input())
y = int(input())
res = 'prime numbers: '
for a in range (x,y+1):
    if all(a % i for i in range(2, a)):
        res+=str(a)  
print(res)

To solve it your way, just replace 0 with 1 as end range as all numbers are divisible by 1 and do a break as suggested by Tomerikoo Method 2:

x = int(input())
y = int(input())
res = 'prime numbers: '
for i in range (x,y+1):
    for j in range (i-1,1,-1):
        if (i%j == 0): 
            break
    else:
        res=res+str(i)
print(res)
Raghul Raj
  • 1,428
  • 9
  • 24
0

You can try with below approach to leverage for else based prime number checking.

import math

x = int(input())
y = int(input()) 
res = 'prime numbers are:'   
for i in range (x,y):
    for j in range (2,int(math.sqrt(i))):
        if (i%j == 0): 
            break              
    else:
        res+=str(i)+","
print(res)

Venkataraman R
  • 12,181
  • 2
  • 31
  • 58