Skip to content
Advertisement

Program to find the nth prime number

I wrote a code in python to find the nth prime number.

print("Finds the nth prime number")
def prime(n):
    primes = 1
    num = 2
    while primes <= n:
            mod = 1
            while mod < (num - 1):
                    ptrue = 'true'
                    if num%(num-mod) == 0:
                            ptrue = 'false'
                            break
                    mod += 1
            if ptrue == 'true':
                    primes += 1
    return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)

The code looked fine to me, but it returns an error when I run it:

  Traceback (most recent call last):            
  File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>           
  print(prime(nth))           
  File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime          
  if ptrue == 'true':
  UnboundLocalError: local variable 'ptrue' referenced before assignment  

It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here… Can anyone help?

Advertisement

Answer

how about using Boolean ? and initalize ptrue out of while loop

print("Finds the nth prime number")
def prime(n):
    primes = 1
    num = 2
    while primes <= n:
            mod = 1
            ptrue = True
            while mod < (num - 1):
                    if num%(num-mod) == 0:
                            ptrue = False
                            break
                    mod += 1
            if ptrue == True:
                    primes += 1
    return(num)
nth = int(input("Enter the value of n: "))

print prime(nth)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement