Find nth prime number in python
Hi, today we will learn about how to find an nth prime number in python. Finding a prime number is very easy in python. A prime number is a number which can only be divided by 1 and the number itself.
Python program to find nth prime number
Code :
n = int(input('Enter : ')) prime_numbers = [2,3] i=3 if(0<n<3): print(n,'th Prime Number is :',prime_numbers[n1]) elif(n>2): while (True): i+=1 status = True for j in range(2,int(i/2)+1): if(i%j==0): status = False break if(status==True): prime_numbers.append(i) if(len(prime_numbers)==n): break print(n,'th Prime Number is :', prime_numbers[n1]) else: print('Please Enter A Valid Number')
Output :
Explanation :
 At first, we take the input into the ‘n’ variable.
 We create a python list variable ‘prime_numbers’.
 Initially, we store 2,3 into the ‘prime_numbers’ variable.
 We create an ‘i’ variable. Initially, we store 3 into the ‘i’ variable.
 We create an if condition. If the value of n is greater than 0 and less than 3, it means if the value of n in between 1 to 2 then the operation will be performed. If the condition satisfied then print the list prime_numbers’s n1 th position value.
 We create an elif condition. If the value is greater than 2 then the task is performed.
 We create an infinite While Loop. For storing the prime number into the ‘prime_numbers’ variable.
 increase the value of ‘i’ by one.
 We create a boolean variable ‘status’. Initially, it is ‘True’.
 We create a For Loop. The starting value of for loop variable ‘j’ is 2 and ending with (half+1) of the ‘i’ value. This for loop is used for checking the ‘i’ number is prime or not prime.
 If the remainder of (‘i’ value / ‘j’ value) is Zero then it not be a prime number. And break the for loop and ‘status‘ will be ‘False’.
 For all value of ‘j’, if the remainder not going to zero then the ‘status‘ will be ‘True’.
 We check if the status True then it is a prime number. And it stored into the ‘prime_numbers’.
 We check if the length of the list is equal to the ‘n’ value then the while loop will break.
 After breaking the while loop we print the nth prime number.
 We create an else section if the user types any wrong or negative value then program will print ‘Please Enter A Valid Number’.

In this whole process, we can easily find the nth prime number.
You may like to read :
 Catalan Number in Python – Iterative Approach (Factorial)
 Check whether two strings are anagram of each other using Python 3.x or earlier
Line 9: why not just use i+=2? It yields the same results.
not need to run upto i/2+1 we can run upto sqrt(i)+1