2

I made a program to find a prime number and store in list. Now i want to print the exact position of the prime number For eg. in the range of 2 to 20 If i take the input 6 it should print 13 not 17.

q=[]
for num in range(1,101):
    if num>1:
        if all(num%i!=0 for i in range(2,int(num**0.5+1))):
            q.append(num)
0

2 Answers 2

2

Just deduct 1 from the index:

print(q[6-1]) # -> 13

lists are zero-based so if you are going to use one-based indexing you need to simply subtract 1, you should also maybe handle the case where a user enters 0.

You can also start your range at 3 and use a step of 2 to get your primes:

q = [2]
for num in range(3, 101, 2):
    if num > 1:
        if all(num % i != 0 for i in range(3, int(num ** 0.5 + 1), 2)):
            q.append(num)
Sign up to request clarification or add additional context in comments.

2 Comments

so what will you suggest for zero?
@YaShChaudhary, if you truly wanted to have a one-based array then an indexerror would be appropriate but it is completely dependant on what you are trying to acheive
2
q=[]
for num in range(1,101):
    if num>1:
        if all(num%i!=0 for i in range(2,int(num**0.5+1))):
             q.append(num)
index  = 6
print q[index-1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.