对于类,我们得到了一个充满语法错误的源代码。我修复了一些更明显的语法问题。这是迄今为止的代码:
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
myList如何定义?
答案 0 :(得分:1)
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()
编辑:同样适用于num
变量
答案 1 :(得分:1)
考虑阅读Python中scope的内容:
[...]通常,本地范围引用(文本)当前函数的本地名称。在外部函数中,本地作用域引用与全局作用域相同的名称空间:模块的名称空间。 [...]
您的变量位于main
函数的范围内,该函数是本地范围。您无法访问本地范围之间的变量。作为Tim Castelijns showed in his answer,一种可能的解决方案是将列表作为参数传递。