# Python – UnboundLocalError：分配前引用了局部变量&#39;p&#39;。 While循环根据我输入的时间提供不同的输出Python – UnboundLocalError: local variable 'p' referenced before assignment. While Loop giving different outputs depending when I input

def retest2():
print "Type in another chapter title! Or type \"Next\" to move on."
print "--------------------------------------------------\nChapters in books are usually given the cardinal numbers 1, 2, 3, 4, 5, 6 and so on.\n\nBut I have decided to give my chapters prime numbers 2, 3, 5, 7, 11, 13 and so on because I like prime numbers.\n\nType in the chapter title of my book (a prime number) and I will tell you what cardinal number the chapter is."
chapter = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233)
while True:
prime = raw_input("\n")
if "next"  == prime.lower() or "Next" == prime.lower():
print "--------------------------------------------------\nOnto the next thing."
break
try:
p = int(prime)
if p in chapter:
print "Chapter ",chapter.index(p) + 1
retest2()
except ValueError:  #invalid input
print "That is not one of my chapter numbers because {0} is not a prime number found in my book. Try again.".format(prime)

if p not in chapter:    #input is integer, but not a prime number within my range of primes
print "That is not one of my chapter numbers because {0} is not a prime number found in my book. Try again.".format(prime)

That is not one of my chapter numbers because okay is not a prime number found in my book. Try again.
Traceback (most recent call last):
File "trial.py", line 83, in <module>
File "trial.py", line 80, in primenumbers2
if p not in chapter:    #input is integer, but not a prime number within my range of primes
UnboundLocalError: local variable 'p' referenced before assignment

## 3 个回复3

### ===============>>#1 票数：3

“我按照您的建议进行了操作，并用p = None初始化了p，这很好地解决了我的第一个问题。但是，如果我输入正确，我将得到2行，即...，那可能是因为此参数同时满足了该章中的“例外”和“如果不是p ...我该如何避免呢？”

except ValueError:  #invalid input
print "That is ...'
continue

p=None
try:
# do smth
except:
# do smth

### ===============>>#3 票数：0

except ValueError:  #invalid input
print "That is ...'
continue

3回复

3回复

4回复

1回复

1回复

1回复

2回复

2回复

1回复

2回复