调用函数时出现UnboundLocalError

0 投票
1 回答
519 浏览
提问于 2025-05-10 21:20

我正在做一个作业,这个作业需要输入一个数字,然后告诉用户这个数字是否是有效的社会保险号码(SIN)。但是我的程序无法运行,出现了这个错误:

UnboundLocalError: 本地变量 'isdigit' 在赋值之前被引用。

我该怎么解决这个问题呢?

from sinmodule import is_valid

def main():
    print "SIN Validator"
    print "============="


   isdigit()

def isdigit():

    int_str = str(sinnumber)
    length = (len(int_str))        

    number = raw_input("Please Enter SIN (Q to quit):")

    while length != 8:
        print "You did not enter 'Q' or a number."
        sinnumber = raw_input("Please Enter SIN (Q to quit):")

    if length == 8:
        if status == True:
            print "The number",number," IS a valid SIN."
        else:
            print "The number",number,"is NOT a valid SIN."

    if number == "Q":
        print "Good-bye!"

main()

相关文章:

  • 暂无相关问题
暂无标签

1 个回答

0

在你的代码中,使用 isdigit 时应该不会遇到 UnboundLocalError 的问题。因为它在一个地方定义,然后在另一个函数里被调用。这里的作用域规则是适用的。

不过,在你使用变量 sinnumber 时,它还没有被定义:

def isdigit():

    int_str = str(sinnumber)  # <--- here this is unbound
    length = (len(int_str))

    number = raw_input("Please Enter SIN (Q to quit):")

    while length != 8:
        print "You did not enter 'Q' or a number."
        sinnumber = raw_input("Please Enter SIN (Q to quit):") #<-defined here
    ...

你需要把这个定义(在 while 循环里的)移动到使用它之前。同时,检查一下你是怎么“增长” sinnumber 的,以及你在哪里更新 length

撰写回答