UnboundLocalError: local variable 'prime' referenced before assignment
我得到这个错误
UnboundLocalError : local variable 'prime' referenced before assignment
使用此代码查看数字是否为质数。我该怎么修?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import math def is_prime(n): if n == 2: prime = 1 if n % 2 == 0 or n <= 1: prime = 0 sqr = int(math.sqrt(n)) + 1 for divisor in range(3, sqr, 2): if n % divisor == 0: prime = 0 if prime != 0: print("Prime") if prime == 0: print("Not prime") is_prime(int(input("Number?"))) |
如果所有条件都不成功,您就不会设置
另外,你会对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def is_prime(n): if n == 2: prime = True elif n % 2 == 0 or n <= 1: prime = False else: sqr = int(math.sqrt(n)) + 1 for divisor in range(3, sqr, 2): if n % divisor == 0: prime = False break else: prime = True if prime: print("Prime") else: print("Not prime") |