I wrote a code in python to find the nth prime number.
JavaScript
x
18
18
1
print("Finds the nth prime number")
2
def prime(n):
3
primes = 1
4
num = 2
5
while primes <= n:
6
mod = 1
7
while mod < (num - 1):
8
ptrue = 'true'
9
if num%(num-mod) == 0:
10
ptrue = 'false'
11
break
12
mod += 1
13
if ptrue == 'true':
14
primes += 1
15
return(num)
16
nth = int(input("Enter the value of n: "))
17
print(prime(nth)
18
The code looked fine to me, but it returns an error when I run it:
JavaScript
1
7
1
Traceback (most recent call last):
2
File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>
3
print(prime(nth))
4
File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime
5
if ptrue == 'true':
6
UnboundLocalError: local variable 'ptrue' referenced before assignment
7
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
JavaScript
1
19
19
1
print("Finds the nth prime number")
2
def prime(n):
3
primes = 1
4
num = 2
5
while primes <= n:
6
mod = 1
7
ptrue = True
8
while mod < (num - 1):
9
if num%(num-mod) == 0:
10
ptrue = False
11
break
12
mod += 1
13
if ptrue == True:
14
primes += 1
15
return(num)
16
nth = int(input("Enter the value of n: "))
17
18
print prime(nth)
19