繁体   English   中英

Python – UnboundLocalError:分配前引用了局部变量'p'。 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."
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()

我在考虑这个程序时问了一个类似的问题( Python –变量既是int又是str ),但是现在我遇到了两个不同的问题。 当我在while循环中输入诸如okay类的随机字符串作为我的第一个输入while ,我收到一条错误消息:

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. That is not one of my chapter numbers because okay is not a prime number found in my book. Try again.

对于您在上面的注释中提到的第二个错误:(我尚无法注释,我不知道该如何应对)
“我按照您的建议进行了操作,并用p = None初始化了p,这很好地解决了我的第一个问题。但是,如果我输入正确,我将得到2行,即...,那可能是因为此参数同时满足了该章中的“例外”和“如果不是p ...我该如何避免呢?”

对于无效输入,您会收到此错误,因为它会第一次打印出无效输入,但是代码会继续检查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个字符以下。 它使其他编码人员更容易阅读和遵循您的代码。

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

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

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

添加continue似乎更有意义:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM