Python – UnboundLocalError: local variable 'p' referenced before assignment. While Loop giving different outputs depending when I input

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."
def primenumbers1():
    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."
def primenumbers2():
    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)
primenumbers1()
primenumbers2()

我针对这个程序提出了类似的问题 (),但现在我遇到了几个不同的问题。当我在此 while 循环中输入一个随机字符串(例如 okay 作为我的第一个输入时,我收到一条错误消息:

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>
    primenumbers2()
  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

然而,当我在稍后的输入中输入 okay 时,它起作用了。

另一个错误是在这个循环中,如果我还没有输入质数,然后输入okay,输出是两行That is not one of my chapter numbers because okay is not a prime number found in my book. Try again.

当您在第一个循环中使用 except ValueError: #invalid input 处理异常时,您没有定义 p

添加 continue 似乎更有意义:

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

您正在 try 块中初始化 p,但在 except 中的代码运行后尝试使用它。如果你得到 ValueError,你就会得到 p was referenced before assignment如何解决:try

之前初始化p
p=None
try:
    # do smth
except:
    # do smth

对于你在上面评论中提到的第二个错误:(我还不能评论,我不知道怎么回复)
"I did what you suggested and initialized p with p=None and that worked well to get rid of my first problem. However, if I enter okay I get 2 lines of That is..., and that's probably because this argument satisfies both the except and the if p not in chapter... How can I avoid this?"

你收到无效输入的错误,因为它第一次打印无效输入,但随后代码继续检查 p 是否不在章节中,如果不在,它会再次打印。

你想做的是找到一些方法在异常发生时跳过下一个 if 块。一旦您知道这是一个无效输入,您就不想继续浏览您的章节。

在 python 中,您可以通过添加 continue 语句来完成此操作。 将此添加到 ValueError 的错误处理中,它将阻止您继续检查 p 是否不在章节中是否存在无效输入。

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

您可以在此处阅读有关 continue 语句的更多信息,我建议您在使用前先阅读! https://docs.python.org/2/reference/simple_stmts.html#continue

我还想提一下,在 python 中,惯例是将行保持在 80 个字符以下。它使其他编码人员更容易阅读和遵循您的代码。