我在python中编写了一个代码来找到第n个素数。程序找到第n个素数
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)
的代码看起来没什么问题,但它返回一个错误,当我运行它:
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
,就好像它是想说我指在以ptrue在我看来,即使我不是。这里有什么问题......任何人都可以帮忙吗?
你只需要添加'ptrue =“true”'到while循环的顶部 –
谢谢,这确实解决了这个问题,但是我的代码似乎没有工作......它只是为每个n的值打印出2 ...什么有这个吗? – AvZ
你从来没有从其''2'的初始值改变num。 –