Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试调用函数时发生UnboundLocalError_Python - Fatal编程技术网

Python 尝试调用函数时发生UnboundLocalError

Python 尝试调用函数时发生UnboundLocalError,python,Python,我正在做一个赋值,它接受一个数字并告诉用户它是否是一个有效的SIN数字。我无法运行我的程序,因为: UnboundLocalError:赋值前引用了局部变量“isdigit” 我该如何解决这个问题 from sinmodule import is_valid def main(): print "SIN Validator" print "=============" isdigit() def isdigit(): int_str = str(sinnu

我正在做一个赋值,它接受一个数字并告诉用户它是否是一个有效的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()

您的代码中的
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
    ...
def isdigit():

int_str=str(sinnumber)#我遇到了另一个问题。第8行的
isdigit()
缩进错误,因此程序无法运行。如果这个调用实际上一直在左边,那么问题是在定义函数之前调用它。如果它在
main
内,那么您就可以。。。但是您将遇到未定义的
sinnumber
问题。