-1

I'm really new to python, so I'm sorry for the low level question..

my current code is

x = input("lower number:")
y = input("higher number:")
a=list(range(int(x), int(y)+1))
print(a)
for i in range (int(x), int(y)+1):
    number=True
    if i==1:
        number = False
    for j in range (2, i):
        if i%j==0:
            number = False
            break
    if number:
        print(i)

and the output comes out like this

lower number:1
higher number:10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2
3
5
7

I want my output to look like [2,3,5,7] instead of the current output.

Peter
  • 21
  • 1
  • create empty list before `for`-loop - `your_list = []` , next use `your_list.append(i)` instead of `print(i)` and after `for`-loop use `print(your_list)` – furas May 08 '20 at 02:07

2 Answers2

2

Create a list and append your numbers to it.

x = input("lower number:")
y = input("higher number:")
a = list(range(int(x), int(y) + 1))
o = []

for i in range (int(x), int(y) + 1):
    number = True

    if i==1:
        number = False

    for j in range (2, i):
        if i % j ==0:
            number = False
            break
    if number:
        o.append(i)

print(o)
Tigran
  • 632
  • 1
  • 5
  • 21
2

Adding onto the answer posted by @Tigran, but with an edit

OP wanted the output to appear as [2,3,5,7], basically without spaces. So on top of the code snippet posted in his (@Tigran) answer,

x = input("lower number:")
y = input("higher number:")
a = list(range(int(x), int(y) + 1))
o = []

for i in range (int(x), int(y) + 1):
    number = True

    if i==1:
        number = False

    for j in range (2, i):
        if i % j ==0:
            number = False
            break
    if number:
        o.append(i)

print(o)

you could use the .replace() function. This would appear as

x = input("lower number:")
y = input("higher number:")
a = list(range(int(x), int(y) + 1))
o = []

for i in range (int(x), int(y) + 1):
    number = True

    if i==1:
        number = False

    for j in range (2, i):
        if i % j ==0:
            number = False
            break
    if number:
        o.append(i)

print(str(o).replace(" ", ""))

Note the use of str() to convert the data type to a string in order to remove the whitespace.

Johnny
  • 211
  • 3
  • 15