搜索语法错误

2024-10-03 15:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

对于这个类,我们得到了一个充满语法错误的源代码。我修复了一些更明显的语法问题。以下是迄今为止的代码:

def findNumInList():
    for i in (myList):
        if(myList[i] == num):
            print("Found number %s" %num)

def main():
    myList = [1,25,7,99,12]

    #Gets number from user, and appends it to the existing list
    num = int(input("Enter a number to be added to the end of the list: "))
    myList.append(num)

    #Checks to see if number was successfully added to the list
    findNumInList()
main()

我仍然得到的是:

Traceback (most recent call last):
  File "part1.py", line 16, in <module>
    main()
  File "part1.py", line 15, in main
    findNumInList()
  File "part1.py", line 3, in findNumInList
    for i in (myList):
NameError: global name 'myList' is not defined

我的列表是如何定义的


Tags: thetoinpynumberformaindef
2条回答

考虑阅读一下Python中的scope是什么:

[...]Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the global scope: the module’s namespace. [...]

变量在main函数的作用域中,这是一个局部作用域。不能在局部作用域之间访问变量。作为Tim Castelijns showed in his answer,一个可能的解决方案是将列表作为参数传递

main()首先被调用,列表在那里被定义,但是它只存在于该函数的作用域中,因此findNumInList函数不知道它

解决方案是将列表传递给函数:

def findNumInList(myList, num):
    for i in (myList):
        if(myList[i] == num):
            print("Found number %s" %num)

def main():
    myList = [1,25,7,99,12]

    #Gets number from user, and appends it to the existing list
    num = int(input("Enter a number to be added to the end of the list: "))
    myList.append(num)

    #Checks to see if number was successfully added to the list
    findNumInList(myList, num)
main()

Edit:对于num变量也是如此

相关问题 更多 >