我在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。 –